<template>
  <div class="random">
    <div class="option" style="margin-top: 10px; padding-bottom: 5px;">
      <div class="header">
        <div class="title" :style="{ fontSize: '16px' }">
          <span>|</span>
          <span>基本设置</span>
        </div>
      </div>
      <el-form ref="baseForm" :model="baseForm" label-width="160px">
        <el-form-item label="关联专项检查" required>
          <el-button @click="showNoticeDialog = true" type="primary"
                     :icon="enforce_obj_id > 0 ? 'el-icon-edit' : 'el-icon-plus'" circle></el-button>
          <span v-if="enforce_obj_id > 0" style="margin-left: 10px; color: red;"
                @click="showNoticeDetail">{{enforce_obj_name}}(点击查看专项检查详情)</span>
        </el-form-item>
        <el-form-item label="火灾高危单位数">
          <el-input readonly="readonly" v-model.number="baseForm.risk_num" style="width: 193px; margin-right: 10px;"></el-input>
          <el-button @click="showTag(1)" type="primary">标签设置</el-button>
          <span
              style="margin-left: 10px; color: #409EFF;">*火灾高危单位{{ enforceStat.risk_num }}家，执法人员{{ userStat.reduce((pre, cur) => pre + cur.user_num, 0) }}人</span>
        </el-form-item>
        <el-collapse v-if="validTags['1'] && validTags['1'].length > 0" accordion
                     style="width: 800px; border: 1px solid #EBEEF5; margin-bottom: 15px;">
          <el-collapse-item v-for="(item, index) in validTags['1']" :key="index">
            <template slot="title">
              <el-row style="width: 100%; padding-left: 10px;">
                <el-col :span="18"><span
                    style="color: #1B90FF; font-weight: bolder; margin-right: 8px;">|</span>{{ item.tag_name }}<span
                    style="color: #409EFF">({{ enforce_obj_count['1'][item.id + ''] }})</span></el-col>
                <el-col :span="6" style="text-align: right; padding-right: 10px;">
                  <span>{{ item.percent }}%</span>
                </el-col>
              </el-row>
            </template>
            <div v-if="item.sub_tags && item.sub_tags.length > 0"
                 style="padding-left: 20px; padding-top: 5px; background-color: #f5f7fa;">
              <el-row v-for="(subItem, subIndex) in item.sub_tags" :key="subIndex" type="flex" style="height: 42px;">
                <el-col :span="18">
                  <div>{{ subItem.tag_name }}<span
                      style="color: #409EFF">({{ enforce_obj_count['1'][subItem.id + ''] }})</span></div>
                </el-col>
                <el-col :span="6" style="text-align: right; padding-right: 35px;">
                  <span>{{ subItem.percent }}%</span>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-form-item label="消防安全重点单位数">
          <el-input readonly="readonly" v-model.number="baseForm.focus_num" style="width: 193px; margin-right: 10px;"></el-input>
          <el-button @click="showTag(2)" type="primary">标签设置</el-button>
          <span
              style="margin-left: 10px; color: #409EFF;">*消防安全重点单位{{ enforceStat.focus_num }}家，执法人员{{ userStat.reduce((pre, cur) => pre + cur.user_num, 0) }}人</span>
        </el-form-item>
        <el-collapse v-if="validTags['2'] && validTags['2'].length > 0" accordion
                     style="width: 800px; border: 1px solid #EBEEF5; margin-bottom: 15px;">
          <el-collapse-item v-for="(item, index) in validTags['2']" :key="index">
            <template slot="title">
              <el-row style="width: 100%; padding-left: 10px;">
                <el-col :span="18"><span
                    style="color: #1B90FF; font-weight: bolder; margin-right: 8px;">|</span>{{ item.tag_name }}<span
                    style="color: #409EFF">({{ enforce_obj_count['2'][item.id + ''] }})</span></el-col>
                <el-col :span="6" style="text-align: right; padding-right: 10px;">
                  <span>{{ item.percent }}%</span>
                </el-col>
              </el-row>
            </template>
            <div v-if="item.sub_tags && item.sub_tags.length > 0"
                 style="padding-left: 20px; padding-top: 5px; background-color: #f5f7fa;">
              <el-row v-for="(subItem, subIndex) in item.sub_tags" :key="subIndex" type="flex" style="height: 42px;">
                <el-col :span="18">
                  <div>{{ subItem.tag_name }}<span
                      style="color: #409EFF">({{ enforce_obj_count['2'][subItem.id + ''] }})</span></div>
                </el-col>
                <el-col :span="6" style="text-align: right; padding-right: 35px;">
                  <span>{{ subItem.percent }}%</span>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-form-item label="一般单位数">
          <el-input readonly="readonly" v-model.number="baseForm.police_num" style="width: 193px; margin-right: 10px;"></el-input>
          <el-button @click="showTag(3)" type="primary">标签设置</el-button>
          <span
              style="margin-left: 10px; color: #409EFF;">*一般单位{{ enforceStat.police_num }}家，执法人员{{ userStat.reduce((pre, cur) => pre + cur.user_num, 0) }}人</span>
        </el-form-item>
        <el-collapse v-if="validTags['3'] && validTags['3'].length > 0" accordion
                     style="width: 800px; border: 1px solid #EBEEF5; margin-bottom: 15px;">
          <el-collapse-item v-for="(item, index) in validTags['3']" :key="index">
            <template slot="title">
              <el-row style="width: 100%; padding-left: 10px;">
                <el-col :span="18"><span
                    style="color: #1B90FF; font-weight: bolder; margin-right: 8px;">|</span>{{ item.tag_name }}<span
                    style="color: #409EFF">({{ enforce_obj_count['3'][item.id + ''] }})</span></el-col>
                <el-col :span="6" style="text-align: right; padding-right: 10px;">
                  <span>{{ item.percent }}%</span>
                </el-col>
              </el-row>
            </template>
            <div v-if="item.sub_tags && item.sub_tags.length > 0"
                 style="padding-left: 20px; padding-top: 5px; background-color: #f5f7fa;">
              <el-row v-for="(subItem, subIndex) in item.sub_tags" :key="subIndex" type="flex" style="height: 42px;">
                <el-col :span="18">
                  <div>{{ subItem.tag_name }}<span
                      style="color: #409EFF">({{ enforce_obj_count['3'][subItem.id + ''] }})</span></div>
                </el-col>
                <el-col :span="6" style="text-align: right; padding-right: 35px;">
                  <span>{{ subItem.percent }}%</span>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-form-item label="其他单位数">
          <el-input readonly="readonly" v-model.number="baseForm.other_num" style="width: 193px; margin-right: 10px;"></el-input>
          <el-button @click="showTag(4)" type="primary">标签设置</el-button>
          <span
              style="margin-left: 10px; color: #409EFF;">*其他单位{{ enforceStat.other_num }}家，执法人员{{ userStat.reduce((pre, cur) => pre + cur.user_num, 0) }}人</span>
        </el-form-item>
        <el-collapse v-if="validTags['4'] && validTags['4'].length > 0" accordion
                     style="width: 800px; border: 1px solid #EBEEF5; margin-bottom: 15px;">
          <el-collapse-item v-for="(item, index) in validTags['4']" :key="index">
            <template slot="title">
              <el-row style="width: 100%; padding-left: 10px;">
                <el-col :span="18"><span
                    style="color: #1B90FF; font-weight: bolder; margin-right: 8px;">|</span>{{ item.tag_name }}<span
                    style="color: #409EFF">({{ enforce_obj_count['4'][item.id + ''] }})</span></el-col>
                <el-col :span="6" style="text-align: right; padding-right: 10px;">
                  <span>{{ item.percent }}%</span>
                </el-col>
              </el-row>
            </template>
            <div v-if="item.sub_tags && item.sub_tags.length > 0"
                 style="padding-left: 20px; padding-top: 5px; background-color: #f5f7fa;">
              <el-row v-for="(subItem, subIndex) in item.sub_tags" :key="subIndex" type="flex" style="height: 42px;">
                <el-col :span="18">
                  <div>{{ subItem.tag_name }}<span
                      style="color: #409EFF">({{ enforce_obj_count['4'][subItem.id + ''] }})</span></div>
                </el-col>
                <el-col :span="6" style="text-align: right; padding-right: 35px;">
                  <span>{{ subItem.percent }}%</span>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>
    <div class="option" style="margin-top: 10px; padding-bottom: 5px;">
      <div class="header">
        <div class="title" :style="{ fontSize: '16px' }">
          <span>|</span>
          <span>时间设置</span>
        </div>
      </div>
      <el-form ref="timeForm" :model="timeForm" align="left" label-width="100px">
        <div v-for="(item, key) in timeRangeMap" :key="key"
             style="width: 640px; background-color: #F2F2F2; position: relative; margin-bottom: 10px;">
          <div
              style="position: absolute; top: 0; left: 0; width: 0; height: 0; border-top: 50px solid #409EFF; border-right: 50px solid transparent;"></div>
          <div
              style="position: absolute; top: 0; left: 0; font-size: 18px; color: #FFF; font-weight: bold; padding: 5px;">
            {{ dateFormat('mm', item['min']) }}
          </div>
          <div style="padding: 10px 50px; font-size: 14px;">{{ dateFormat('YYYY-mm-dd HH:MM:SS', item['min']) }} ~
            {{ dateFormat('YYYY-mm-dd', item['max']) }} 23:59:59
          </div>
          <el-row type="flex" style="padding: 0 0;">
            <el-col :span="12">
              <el-form-item label="时间" required style="margin-bottom: 10px;">
                <el-date-picker
                    v-model="timeRangeMap[key].task_execute_time"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    :picker-options="{disabledDate: (time) => {
                      return time.getTime() < item['min'].getTime() || time.getTime() > item['max'].getTime()
                    }}"
                    placeholder="选择规则生成时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检查占总比例" style="margin-bottom: 10px;">
                <el-input-number :min="1" :max="100" v-model.number="timeRangeMap[key].percent" style="width: 193px; margin-right: 10px;"
                          placeholder="请设置百分比"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="saveRule">确定</el-button>
    </div>
    <el-dialog :visible.sync="showNoticeDialog" v-if="showNoticeDialog" width="70%" :title="'关联专项检查'">
      <special-notice-select :notice_id="enforce_obj_id" @handleSelect="handleSelect"></special-notice-select>
    </el-dialog>
    <el-dialog :visible.sync="showTagDialog" v-if="showTagDialog" :title="'标签设置'" width="70%">
      <special-rule-setting-tag :enforce_obj_count="enforce_obj_count[type]" :type="type" :tags="tempTags"
                                @handleCancel="showTagDialog = false" @handleSubmit="setTag"></special-rule-setting-tag>
    </el-dialog>
    <el-dialog :visible.sync="showNoticeDetailDialog" width="80%" v-if="showNoticeDetailDialog" :title="'专项检查详情'">
      <special-notice-detail :notice_id="enforce_obj_id"></special-notice-detail>
    </el-dialog>
  </div>
</template>

<script>
import SpecialRuleSettingTag from './component/SpecialRuleSettingTag'
import SpecialNoticeSelect from './component/SpecialNoticeSelect'
import SpecialNoticeDetail from './SpecialNoticeDetail'
import {statUser} from "@/api/base";
import {statEnforce} from "@/api/resource";
import {getTags, saveRule, statBatchTag, statTag} from "@/api/random";
import {dateFormat} from "@/utils/tool";
import {Loading} from "element-ui";

export default {
  components: {
    SpecialRuleSettingTag,
    SpecialNoticeSelect,
    SpecialNoticeDetail
  },
  data() {
    return {
      dateFormat,
      enforce_obj_id: 0,
      enforce_obj_name: '',
      baseForm: {
        risk_num: null,
        focus_num: null,
        police_num: null,
        other_num: null
      },
      enforce_obj_count: {},
      timeForm: {},
      userStat: [],
      enforceStat: {},
      tags: {},
      tempTags: [],
      validTags: {},
      type: 0,
      showTagDialog: false,
      showNoticeDialog: false,
      showNoticeDetailDialog: false,
      timeRangeMap: {},
    }
  },
  created() {
    this.loadUserStat()
    this.loadEnforceStat()
    this.loadTags()
  },
  methods: {
    loadUserStat() {
      statUser().then(res => {
        console.log("UserStat", res)
        this.userStat = res
      })
    },
    loadEnforceStat() {
      statEnforce({countType: 2}).then(res => {
        console.log("EnforceStat", res)
        this.enforceStat = res
      })
    },
    loadTags() {
      getTags({page: 1, size: 1000, query: 'level==1'}).then(res => {
        if (res) {
          let tags = res.data || []
          this.tags['1'] = JSON.parse(JSON.stringify(tags))
          this.tags['2'] = JSON.parse(JSON.stringify(tags))
          this.tags['3'] = JSON.parse(JSON.stringify(tags))
          this.tags['4'] = JSON.parse(JSON.stringify(tags))
        }
      })
    },
    handleSelect(enforce_obj) {
      console.log(enforce_obj)
      this.enforce_obj_id = enforce_obj.id
      this.enforce_obj_name = enforce_obj.task_name
      this.showNoticeDialog = false
      let beginTime = new Date(enforce_obj.start_time)
      let endTime = new Date(enforce_obj.end_time)
      let timeRangeMap = this.sliceDateRange(beginTime, endTime)
      console.log('timeRangeMap', timeRangeMap)
      this.timeRangeMap = timeRangeMap
    },
    sliceDateRange(beginTime, endTime) {
      let tempTime = beginTime
      let tempMap = {}
      for (; tempTime.getTime() <= endTime.getTime(); tempTime = this.addDays(tempTime, 1)) {
        let tempMonth = dateFormat('YYYY-mm', tempTime)
        if (!tempMap[tempMonth]) {
          tempMap[tempMonth] = {
            min: tempTime,
            max: tempTime
          }
        }
        if (tempMap[tempMonth]['min'].getTime() > tempTime.getTime()) {
          tempMap[tempMonth]['min'] = tempTime
        }
        if (tempMap[tempMonth]['max'].getTime() < tempTime.getTime()) {
          tempMap[tempMonth]['max'] = tempTime
        }
      }
      return tempMap
    },
    addDays(date, days) {
      let newDate = new Date(date)
      newDate.setDate(newDate.getDate() + days)
      return new Date(newDate)
    },
    showTag(type) {
      let tags = this.tags[type + '']
      let tagIds = tags.map(item => item.id)
      for (let index in tags) {
        if (tags[index].sub_tags && tags[index].sub_tags.length > 0) {
          let subTagIds = tags[index].sub_tags.map(item => item.id)
          tagIds = tagIds.concat(subTagIds)
        }
      }
      let loading = Loading.service({ fullscreen: true, text: '正在加载'})
      let enforce_obj_count = {}
      let tasks = []
      for (let index in tagIds) {
        let tagId = tagIds[index]
        tasks.push(new Promise((resolve, reject) => {
          statTag(tagId, {enforce_obj_type: type, show_recent: false}).then(res => {
            console.log(tagId, res)
            enforce_obj_count[tagId + ''] = res.total
            resolve(res)
          })
        }))
      }
      Promise.all(tasks).then(res => {
        this.enforce_obj_count[type + ''] = enforce_obj_count
        this.type = type
        this.tempTags = this.tags[type + '']
        this.showTagDialog = true
        loading.close()
      })

      // statBatchTag({ids: tagIds.join(','), enforce_obj_type: type, show_recent: false}).then(res => {
      //   this.enforce_obj_count = JSON.parse(res.statics)
      //   this.type = type
      //   this.tempTags = this.tags[type + '']
      //   this.showTagDialog = true
      // })
    },
    setTag(type, tags) {
      console.log(type, tags)
      let flag = this.checkTagSetting(tags)
      if (!flag) {
        return
      }
      this.tags[type + ''] = JSON.parse(JSON.stringify(tags))
      this.validTags[type + ''] = this.filterValidTags(tags)
      this.showTagDialog = false
      let count = this.calcSelectCount(type, tags)
      let baseForm = Object.assign({}, this.baseForm)
      if (type === 1) {
        baseForm.risk_num = count
      } else if (type === 2) {
        baseForm.focus_num = count
      } else if (type === 3) {
        baseForm.police_num = count
      } else if (type === 4) {
        baseForm.other_num = count
      }
      this.baseForm = baseForm
    },
    checkTagSetting(tags) {
      if (tags && tags.length > 0) {
        for (let index in tags) {
          let tag = tags[index]
          if (tag.percent) {
            // 主标签填写了占比，次标签之和不能超100
            if (tag.sub_tags && tag.sub_tags.length > 0) {
              let totalPercent = 0
              for (let subIndex in tag.sub_tags) {
                let subTag = tag.sub_tags[subIndex]
                if (subTag.percent) {
                  totalPercent += subTag.percent
                }
              }
              if (totalPercent > 100) {
                this.$message.warning('标签【' + tag.tag_name + '】下的设置的子标签占比之和不能超100');
                return false
              }
            }
          } else {
            // 主标签未填写占比，不检查次标签
          }
        }
      }
      return true
    },
    filterValidTags(tags) {
      let validTags = []
      for (let index in tags) {
        let tag = tags[index]
        let need = false
        if (tag.sub_tags && tag.sub_tags.length > 0) {
          let sub_tags = []
          for (let subIndex in tag.sub_tags) {
            let subTag = tag.sub_tags[subIndex]
            if (subTag.percent) {
              sub_tags.push(subTag)
            }
          }
          if (sub_tags.length > 0) {
            tag.sub_tags = sub_tags
            need = true
          } else {
            tag.sub_tags = []
          }
        } else {
          tag.sub_tags = []
        }
        if (tag.percent) {
          need = true
        }
        if (need) {
          validTags.push(tag)
        }
      }
      return validTags
    },
    calcSelectCount(type, tags) {
      let totalCount = 0
      for (let index in tags) {
        let tag = tags[index]
        if (tag.percent) {
          totalCount += tag.percent * this.enforce_obj_count[type + ''][tag.id + ''] / 100
        } else {
          if (tag.sub_tags && tag.sub_tags.length > 0) {
            for (let subIndex in tag.sub_tags) {
              let subTag = tag.sub_tags[subIndex]
              if (subTag.percent) {
                totalCount += subTag.percent * this.enforce_obj_count[type + ''][subTag.id + ''] / 100
              }
            }
          }
        }

      }
      return Math.round(totalCount)
    },
    showNoticeDetail() {
      let enforce_obj_id = this.enforce_obj_id
      this.showNoticeDetailDialog = true
      // this.$router.push({
      //   path: '/random/special/notice/detail',
      //   query: {
      //     id: enforce_obj_id
      //   }
      // })
    },
    buildTag(tags) {
      let results = []
      for (let index in tags) {
        let tag = tags[index]
        if (tag.percent) {
          let subTags = []
          for (let subIndex in tag.sub_tags) {
            let subTag = tag.sub_tags[subIndex]
            if (subTag.percent) {
              subTags.push({
                tag_id: subTag.id,
                tag_name: subTag.tag_name,
                percent: subTag.percent,
                tag_levet: subTag.level
              })
            }
          }
          results.push({
            tag_id: tag.id,
            tag_name: tag.tag_name,
            percent: tag.percent,
            tag_levet: tag.level,
            sub_tags: subTags
          })
        }
      }
      return results
    },
    saveRule() {
      if (!this.enforce_obj_id) {
        this.$message.error('请选择关联专项检查')
        return
      }
      // 时间设置比例总和不能大于100
      let totalPercent = 0
      for (let key in this.timeRangeMap) {
        let range = this.timeRangeMap[key]
        if (!range.task_execute_time) {
          this.$message.error('请选择规则生成时间')
          return;
        }
        if (!range.percent) {
          this.$message.error('请设置检查占总比例')
          return;
        }
        totalPercent += range.percent
      }
      if (totalPercent !== 100) {
        this.$message.error('检查占总比例之和必须为100%')
        return;
      }
      let risk_tags = this.buildTag(this.tags['1'])
      let focus_tags = this.buildTag(this.tags['2'])
      let police_tags = this.buildTag(this.tags['3'])
      let other_tags = this.buildTag(this.tags['4'])
      let random_execute_time = []
      for (let key in this.timeRangeMap) {
        let range = this.timeRangeMap[key]
        random_execute_time.push({
          task_month: key,
          task_execute_time: range.task_execute_time,
          percent: range.percent
        })
      }
      let params = {
        notify_id: this.enforce_obj_id,
        task_type: '1',
        ...this.baseForm,
        random_execute_time: random_execute_time,
        risk_tag: risk_tags,
        focus_tag: focus_tags,
        police_tag: police_tags,
        other_tag: other_tags
      }
      console.log("SpecialRule", params)
      saveRule(params).then(res => {
        this.$message.success('规则设置成功')
        this.$router.replace({
          path: '/random/special/rule'
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/variables.scss';

.option {
  padding: 16px 16px 0;
  background-color: #FFFFFF;
  border-radius: 10px;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .title {
    color: #000000;
    margin-bottom: 15px;

    & > span:first-child {
      color: $blueColor;
      font-weight: bolder;
      margin-right: 8px;
    }
  }
}
</style>
