<template>
  <a-modal
    ref="auditModal"
    title="指标选择"
    :destroy-on-close="true"
    :visible="visible"
    width="1350px"
    :body-style="{
      padding: '0 24px',
    }"
    :class="$style.selectModal"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <!-- 高级搜索组件 -->
    <audit-advanced-query
      :expand="expand"
      :search-data="formData"
      ref-name="searchform"
      :search-style="{
        height: '220px',
        left: '20px',
        top: '100px !important',
        margin: 'auto',
      }"
      :search-fun="handleSearch"
      @searchedClick="searchedClick"
      @resetForm="resetForm"
    >
      <template>
        <a-col :span="12">
          <a-form-model-item :label="'\u2003\u2003业务分类'">
            <sd-tree-picker
              v-model="formData.busiClass"
              single
              :load-tree-data="loadTreeData"
              :class="$style.treeSelect"
              :data-source="[]"
              :selected-keys="[]"
            >
            </sd-tree-picker>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item :label="'指标名称'">
            <a-input v-model="formData.indiName" allow-clear />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item :label="'指标时间维度'">
            <a-select v-model="formData.indiFrequency" :options="optionsArray.optionsFrequency" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item :label="'监测范围'">
            <a-select v-model="formData.monitorRange" :options="optionsArray.optionsRange" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item :label="'\u2003\u2003监测单位'">
            <sd-group-picker v-model="formData.monitorDept" :read-only="false" />
          </a-form-model-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-model-item :label="'预警状态'" prop="alertStatus">
            <a-select v-model="formData.alertStatus" :options="optionsArray.optionsStatus" />
          </a-form-model-item>
        </a-col> -->
      </template>
    </audit-advanced-query>
    <!-- 列表 -->
    <sd-data-table
      ref="dataTable"
      :row-key="'id'"
      :filter-expressions="expressions"
      :columns="columns"
      :show-advance-query="true"
      form-id="kpiIndiDef"
      :data-url="dataUrl"
      show-selection
      :modal-props="{ class: 'noBottom' }"
      :search-fields="['indiName']"
      :process-res="processRes"
      @searchbtnClick="searchbtnClick"
    >
      <div slot="dataTime" slot-scope="text, record">
        {{ record.year + '年' + record.dataPeriod }}
      </div>
      <div
        slot="alertStatus"
        slot-scope="text, record"
        :title="
          '\n红:' +
            record.redStrs +
            '\r\n黄:' +
            record.yellowStrs +
            '\r\n绿:' +
            record.grenStrs +
            ' '
        "
      >
        <div v-if="record.alertStatus === 'D'" :class="$style.status">无</div>
        <div v-else-if="record.alertStatus === 'A'" :class="$style.redstatus">红</div>
        <div v-else-if="record.alertStatus === 'B'" :class="$style.ystatus">黄</div>
        <div v-else-if="record.alertStatus === 'C'" :class="$style.lstatus">绿</div>
      </div>
      <div slot="indiUnit" slot-scope="text, record">
        {{ text }}
      </div>
    </sd-data-table>
  </a-modal>
</template>

<script>
import { message } from '@/common/one-ui'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import KpiService from '../kpi-service'
import kpiAnalysisFormService from './kpi-analysis-form-service'
import components from './_import-components/kpi-analysis-select-modal-import'

export default {
  name: 'KpiAnalysisSelectModal',
  metaInfo: {
    title: '指标选择器',
  },
  components: {
    auditAdvancedQuery,
    ...components,
  },
  mixins: [auditAdvancedQueryMixins],
  props: {
    // 是否显示
    visible: {
      type: Boolean,
      default: false,
    },
    // 过滤条件
    selectExpressions: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 列表类型  指标/异常指标
    type: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      dataUrl: '',
      listExpressions: [],
      treeparams: {
        configId: 101,
      },
      optionsArray: {
        optionsFrequency: [], // 指标时间维度下拉选项
        optionsStatus: [], // 指标状态下拉选项
        optionsRange: [], // 监测范围
        optionsindiUnit: [], // 指标值单位
      },
      formData: {
        indiName: '',
        busiClass: [],
        alertStatus: '',
        indiFrequency: '',
        monitorRange: '',
        monitorDept: '',
      },
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '指标名称',
          dataIndex: 'indiName',
        },
        {
          title: '业务分类',
          dataIndex: 'busiClassName',
        },
        {
          title: '维护单位',
          dataIndex: 'createDeptName',
        },
      ],
    }
  },
  computed: {
    expressions() {
      return this.selectExpressions.concat(this.listExpressions)
    },
  },
  mounted() {
    // 获取数据字典-状态
    this.getDictionary('ALERT_STATUS', 'optionsStatus')
    // 获取数据字典-指标时间维度
    this.getDictionary('KPI_FREQUENCY', 'optionsFrequency')
    // 获取数据字典-监测范围
    this.getDictionary('MONITOR_RANGE', 'optionsRange')
    // 指标值单位
    this.getDictionary('INDI_UNIT', 'optionsindiUnit')
    // 判断类型
    if (this.type === 'yc') {
      this.dataUrl = 'api/xcoa-mobile/v1/kpiindimonitor/getAbnormalIndiVal'
      this.columns = [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '业务分类',
          dataIndex: 'busiClass',
          width: '150px',
          customRender: (text) => {
            if (text.indexOf('[') !== -1) {
              const data = JSON.parse(text)
              if (data.length > 0) {
                return JSON.parse(text)[0].name
              }
              return ''
            }
            return text
          },
        },
        {
          title: '指标名称',
          dataIndex: 'indiName',
          width: '150px',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '指标时间维度',
          dataIndex: 'indiFrequency',
        },
        {
          title: '监测单位',
          dataIndex: 'monitorDeptStr',
        },
        {
          title: '数据时期',
          dataIndex: 'dataTime',
          scopedSlots: { customRender: 'dataTime' },
        },
        {
          title: '指标值',
          dataIndex: 'indiVal',
        },
        {
          title: '指标值单位',
          dataIndex: 'indiUnit',
          scopedSlots: { customRender: 'indiUnit' },
        },
        {
          title: '预警状态',
          dataIndex: 'alertStatus',
          scopedSlots: { customRender: 'alertStatus' },
        },
      ]
    } else {
      this.dataUrl = '    api/xcoa-mobile/v1/kpi-indi-def/list'
    }
  },
  methods: {
    // 获取指标值单位
    getIndiUnitValue(val) {
      return this.optionsArray.optionsindiUnit.find((item) => {
        return item.value === val
      })?.label
    },
    // 数据返回后，整理response对象
    processRes(res) {
      if (this.type === 'yc') {
        if (res.data) {
          res.data.forEach((item) => {
            if (item.monitorDeptNameStrs.indexOf(',') > -1) {
              const monitorDepts = item.monitorDeptNameStrs.split(',')
              const monitorDeptsid = item.monitorDeptIdStrs.split(',')
              const alertStatus = item.alertStatus.split(',')
              const indiUnit = item.indiUnit.split(',')
              const indiVal = item.indiVal.split(',')
              const indiNo = item.indiNo.split(',')
              const ids = item.id.split(',')
              const indiId = item.indiId
              const indiName = item.indiName
              const year = item.year.split(',')
              const dataPeriod = item.dataPeriod.split(',')
              const redStrs = item.redStrs.split('*~*')
              const yellowStrs = item.yellowStrs.split('*~*')
              const grenStrs = item.grenStrs.split('*~*')
              monitorDepts.forEach((mitem, mindex) => {
                if (mindex !== 0) {
                  res.data.push({
                    id: ids[mindex],
                    busiClass: item.busiClass,
                    indiName: item.indiName,
                    indiFrequency: item.indiFrequency,
                    monitorRange: item.monitorRange,
                    monitorDeptStr: mitem,
                    alertStatus: alertStatus[mindex],
                    indiNo: indiNo[mindex],
                    indiVal: indiVal[mindex],
                    indiUnit: indiUnit[mindex],
                    indiId: indiId,
                    indiNameChildren: indiName,
                    year: year[mindex],
                    dataPeriod: dataPeriod[mindex],
                    redStrs: redStrs[mindex],
                    yellowStrs: yellowStrs[mindex],
                    grenStrs: grenStrs[mindex],
                  })
                } else {
                  // 首级
                  item.monitorDeptStr = mitem // 监测单位
                  item.alertStatus = alertStatus[mindex]
                  item.indiVal = indiVal[mindex]
                  item.indiUnit = indiUnit[mindex]
                  item.indiNo = indiNo[mindex]
                  item.id = ids[mindex]
                  item.year = year[mindex]
                  item.dataPeriod = dataPeriod[mindex]
                  item.redStrs = redStrs[mindex]
                  item.yellowStrs = yellowStrs[mindex]
                  item.grenStrs = grenStrs[mindex]
                }
              })
            } else {
              item.monitorDeptStr = item.monitorDeptNameStrs
            }
          })
        }
      }
      return res
    },
    handleOk() {
      const rows = this.$refs.dataTable.getSelectedRows()
      this.$emit('handleOk', rows)
    },
    handleCancel(event) {
      this.$emit('handleCancel', event)
    },
    // 获取用于选择的业务类型分类树
    loadTreeData(id) {
      const topDepId = !id ? 0 : id
      const params = {
        type: this.treeparams.type,
      }
      return KpiService.getCategoryTree(topDepId, this.treeparams, params)
        .then((res) => {
          const treeNode = res.data
          return this.mapCategoryItems(treeNode)
        })
        .catch((e) => {
          message.error({ content: '应用类型获取失败' })
        })
    },
    mapCategoryItems(items) {
      return (items || []).map((item) => {
        const result = {
          id: item.id + '',
          name: item.text,
          // checkable: true,
          isLeaf: item.leaf,
          checkable: !item.expandable,
        }
        return result
      })
    },
    // 获取数据字典
    getDictionary(id, fieldName) {
      return kpiAnalysisFormService
        .getDictValue(id)
        .then((res) => {
          if (res.data) {
            res.data.forEach((item) => {
              this.optionsArray[fieldName].push({
                label: item.name,
                value: item.id,
              })
            })
          }
        })
        .catch((e) => {
          message.error({ content: '数据字典获取失败' })
        })
    },
    // 重置查询
    resetForm() {
      this.listExpressions = []
      this.formData = {
        indiName: '',
        busiClass: [],
        alertStatus: '',
        indiFrequency: '',
        monitorRange: '',
        monitorDept: '',
      }
    },
    // 查询
    handleSearch() {
      this.listExpressions = []
      if (this.type === 'yc') {
        this.expressions.push({
          dataType: 'long',
          name: 'creationTime',
          op: 'ge',
          longValue: `${new Date(new Date().getFullYear() - 1 + '-01-01 00:00:00').getTime()}`,
        })
      }
      // 业务分类
      if (this.formData.busiClass[0]) {
        this.listExpressions.push({
          dataType: 'str',
          name: 'busiClass',
          op: 'eq',
          stringValue: `${this.formData.busiClass[0].name}`,
        })
      }
      // 指标名称
      if (this.formData.indiName) {
        this.listExpressions.push({
          dataType: 'str',
          name: 'indiName',
          op: 'like',
          stringValue: `${this.formData.indiName}`,
        })
      }
      // 指标时间维度
      if (this.formData.indiFrequency) {
        this.listExpressions.push({
          dataType: 'str',
          name: 'indiFrequency',
          op: 'eq',
          stringValue: `${this.formData.indiFrequency}`,
        })
      }
      // 监测范围
      if (this.formData.monitorRange) {
        this.listExpressions.push({
          dataType: 'str',
          name: 'monitorRange',
          op: 'eq',
          stringValue: `${this.formData.monitorRange}`,
        })
      }
      // 监测单位
      if (this.formData.monitorDept[0]) {
        let deptnames = ''
        this.formData.monitorDept.forEach((item) => {
          if (deptnames === '') {
            deptnames = item.name
          } else {
            deptnames = deptnames + ',' + item.name
          }
        })
        this.listExpressions.push({
          dataType: 'str',
          name: 'monitorDept',
          op: 'eq',
          stringValue: `${deptnames}`,
        })
      }
      // 预警状态
      if (this.formData.alertStatus) {
        this.expressions.push({
          dataType: 'str',
          name: 'alertStatus',
          op: 'eq',
          stringValue: `${this.formData.alertStatus}`,
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.tree-select {
  :global .ant-select {
    padding: 0;
  }
}
.select-modal {
  :global(.ant-table) {
    min-height: 300px;
  }
}
.status {
  width: 25px;
  height: 25px;
  background-color: #aaaaaa;
  margin-left: 20px;
  color: #fff;
  padding-left: 4px;
  border-radius: 3px;
}
.redstatus {
  width: 25px;
  height: 25px;
  background-color: #fb0606;
  margin-left: 20px;
  color: #fff;
  padding-left: 4px;
  border-radius: 3px;
}
.ystatus {
  width: 25px;
  height: 25px;
  background-color: #fff600;
  margin-left: 20px;
  color: #fff;
  padding-left: 4px;
  border-radius: 3px;
}
.lstatus {
  width: 25px;
  height: 25px;
  background-color: #8dcb98;
  margin-left: 20px;
  color: #fff;
  padding-left: 4px;
  border-radius: 3px;
}
</style>
