<template>
  <div :class="$style.searchdiv">
    <a-card :class="$style.searchWrap">
      <a-form-model
        ref="advancedSearchForm"
        class="ant-advanced-search-form"
        :model="form"
        :rules="rules"
        v-bind="formItemLayout"
      >
        <a-row :gutter="24" :class="$style.antformitem">
          <a-col :span="24" :class="$style.deptCol">
            <a-form-model-item label="监测单位" prop="dept">
              <sd-group-picker v-model="form.dept" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="时间维度" prop="date">
              <a-select v-model="form.date" :options="dateOptions" @change="dateChange"></a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" style="margin-bottom: 5px;">
            <a-form-model-item label="指标名称" prop="name">
              <a-select
                v-model="form.name"
                mode="multiple"
                :open="false"
                @focus="showSelectName"
                @change="selectChange"
              ></a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="日期时间" prop="dateTime">
              <a-range-picker
                v-model="form.dateTime"
                :disabledDate="disabledDate"
                @calendarChange="calendarPriceRangeChange"
                @change="changePriceRangeDate"
              ></a-range-picker>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="16"> </a-col>
          <a-col :class="$style.searchbutton" :span="8">
            <div class="reportbuttonContent" style="margin-right:15%">
              <a-button @click="handleReset">重置</a-button>
              <a-button type="primary" html-type="submit" @click="submitForm">查询</a-button>

              <a-button type="primary" @click="exportData">导出</a-button>
              <input id="normal" type="text" style="border: none;width: 0;outline: none;" />
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card class="sd-has-table">
      <div v-show="!flag">
        <a-empty />
      </div>
      <div v-for="(oneData, index) in form.name" :key="oneData">
        <div v-show="flag">
          <!-- 图标and列表组件 -->
          <kpi-analysis-form-echarts
            :key="echartsKey"
            :title="oneData"
            :indi-id="form.nameId[index]"
            :params="params"
          ></kpi-analysis-form-echarts>
        </div>
      </div>
    </a-card>

    <!-- 指标选择器 -->
    <kpi-analysis-select-modal
      :visible="visible"
      :select-expressions="selectExpressions"
      @handleCancel="handleCancel"
      @handleOk="handleOk"
    />
  </div>
</template>

<script>
import moment from 'moment'
import { message } from '@/common/one-ui'
import download from '@/common/services/download'
import kpiAnalysisFormEcharts from './kpi-analysis-form-echarts.vue'
import kpiAnalysisSelectModal from './kpi-analysis-select-modal.vue'
import kpiAnalysisFormService from './kpi-analysis-form-service'
import components from './_import-components/kpi-analysis-form-import'

export default {
  name: 'KpiAnalysisForm',
  metaInfo: {
    title: '指标分析',
  },
  components: {
    kpiAnalysisFormEcharts,
    kpiAnalysisSelectModal,
    ...components,
  },
  data() {
    return {
      params: {},
      echartsKey: 0,
      flag: false,
      isCancel: false,
      selectExpressions: [],
      visible: false,
      dateOptions: [], // 时间维度字典
      form: {
        dept: [],
        date: null,
        name: [],
        nameId: [],
        dateTime: [],
      },
      rules: {
        dept: [{ required: true, message: '请选择监测单位', trigger: 'change' }],
        date: [{ required: true, message: '请选择时间维度', trigger: 'change' }],
        name: [{ required: true, message: '请选择指标名称', trigger: 'change' }],
        dateTime: [
          {
            required: true,
            message: '请选择时间范围',
            trigger: 'change',
            validator: this.checkDateTime,
          },
        ],
      },
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      selectPriceDate: '',
    }
  },
  created() {
    // 获取指标时间范围
    kpiAnalysisFormService.getDictValue('KPI_FREQUENCY').then((res) => {
      this.dateOptions = res.data.map((item) => {
        return {
          label: item.name,
          value: item.id,
        }
      })
    })
  },
  methods: {
    changePriceRangeDate() {
      this.selectPriceDate = ''
    },
    calendarPriceRangeChange(date) {
      this.selectPriceDate = date[0]
    },
    disabledDate(current) {
      if (this.selectPriceDate) {
        const selectV = moment(this.selectPriceDate, 'YYYY-MM-DD').valueOf()
        const disabled = current.year() !== new Date(selectV).getFullYear()
        return disabled
      } else {
        return false
      }
    },
    checkDateTime(rule, value, callback) {
      if (value.length === 0) return false
      if (this.form.date === '1') {
        // 日
        const days = moment(value[1]).diff(moment(value[0]), 'days')
        if (days > 30) {
          rule.message = '时间维度为日时，日期范围不能超过30天'
          return false
        }
      } else if (this.form.date === '2') {
        // 周
        const weeks = moment(value[1]).diff(moment(value[0]), 'weeks')
        if (weeks > 30) {
          rule.message = '时间维度为周时，日期范围不能超过30周'
          return false
        }
      }
      return true
    },
    // 日期范围变更时
    dateChange(val) {
      this.form.name = []
      this.form.nameId = []
      this.selectExpressions = [
        {
          dataType: 'str',
          name: 'indiFrequency',
          op: 'eq',
          stringValue: val,
        },
        {
          dataType: 'str',
          name: 'indiStatus',
          op: 'eq',
          stringValue: '1',
        },
      ]
    },
    handleOk(rows) {
      this.form.name = []
      this.form.nameId = []
      rows.forEach((item) => {
        this.form.name.push(item.indiName)
        this.form.nameId.push(item.id)
      })
      this.flag = false
      this.handleCancel()
    },
    handleCancel(event) {
      this.isCancel = true
      this.visible = false
    },
    selectChange(val) {
      const newId = []
      val.forEach((item, index) => {
        if (this.form.name.includes(item)) {
          newId.push(this.form.nameId[index])
        }
      })
      this.form.name = val
      this.form.nameId = newId
    },
    // 显示选择指标名称
    showSelectName(e) {
      if (!this.form.date) {
        message.info('请先选择时间维度', 1)
        return
      }
      if (this.isCancel) {
        this.isCancel = false
        document.querySelector('#normal').focus()
        return
      }
      this.visible = true
    },
    submitForm() {
      this.params = {
        dateStart: moment(this.form.dateTime[0]).format('YYYY-MM-DD'),
        dateEnd: moment(this.form.dateTime[1]).format('YYYY-MM-DD'),
        unitIds: this.form.dept.map((item) => item.code).join(','),
        indiFrequency: this.form.date,
      }
      this.flag = false
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          this.echartsKey++
          this.flag = true
        }
      })
    },
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
      this.flag = false
    },
    // 导出接口
    exportData() {
      // if (this.$refs.dataTable.data.length === 0) {
      //   message.warning('未查询出可导出数据', 1)
      //   return
      // }
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          const data = { ...this.params, indiId: this.form.nameId.join(',') }

          kpiAnalysisFormService
            .exportKpiAssayList(data)
            .then((res) => {
              const url = URL.createObjectURL(res.data)
              download(url, '指标分析导出.xls')
            })
            .catch(() => {
              message.error('导出失败')
            })
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.toptitle {
  color: #404040;
  font-weight: bold;
  font-size: 22px;
  margin-left: calc(50% - 150px);
}
.search-wrap {
  margin-bottom: $padding-lg;
  :global(.ant-advanced-search-form) {
    padding: 0;
    background: transparent;
    border: none;
    :global(.ant-form-item) {
      margin-bottom: 15px;
    }
  }
  :global .ant-divider-horizontal {
    margin: 10px 0;
  }
}
.searchdiv {
  background-color: #f0f2f5;
  height: 100%;
  :global(.sd-has-table.ant-card) {
    min-height: calc(100vh - 350px);
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: calc(100vh - 350px);
      overflow: auto;
    }
  }
  :global(.ant-col-6) {
    width: 220px;
  }
}

.emptyecharts {
  width: 600px;
  height: 400px;
  margin: auto auto;
  text-align: center;
  &::after {
    content: '无数据';
    padding-top: 150px;
    display: block;
  }
}
.echarts {
  width: 100%;
  height: 400px;
  margin: auto auto;
  text-align: center;
}
.piespan {
  margin-left: -600px;
  position: relative;
  .cate {
    position: absolute;
    right: 300px;
    top: 30px;
    z-index: 5;
    // overflow: auto;
    // height: 250px;
    li {
      cursor: pointer;
      list-style: none;
      font-size: 13px;
      line-height: 23px;
      color: #919191;
      padding-left: 15px;
      position: relative;
    }
  }
}
.pdiv {
  height: 14px;
  width: 14px;
  background: #54c5eb;
  border-radius: 11px;
  position: absolute;
  left: -7px;
  top: 5px;
}
.cateli-span {
  color: #0162eb;
  display: inline-block;
  width: 180px;
}
.cateli-point {
  display: inline-block;
  width: 80px;
}
.backicon {
  position: absolute;
  top: 3px;
  left: 5px;
  cursor: pointer;
}
.antformitem {
  :global(.ant-select) {
    padding: 0;
  }
}
.dept-col {
  :global(.ant-col-14) {
    width: calc(80% + -10px);
  }
}
</style>
