<template>
  <div>
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{
          height: '220px',
          left: '20px',
          top: '70px !important',
          width: 'calc(100% - 30px) !important',
          margin: 'auto',
        }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'\u2002\u2002\u2002\u2002业务分类'" prop="busiClass">
              <sd-tree-picker
                v-model="formData.busiClass"
                single
                :load-tree-data="loadTreeData"
                :class="$style.treeSelect"
                a-select
              >
              </sd-tree-picker>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'指标名称'" prop="indiName">
              <a-input v-model="formData.indiName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'指标时间维度'" prop="indiFrequency">
              <a-select v-model="formData.indiFrequency" :options="optionsArray.optionsFrequency" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'监测范围'" prop="monitorRange">
              <a-select v-model="formData.monitorRange" :options="optionsArray.optionsRange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'\u2002\u2002\u2002\u2002监测单位'" prop="monitorDept">
              <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"
        :actions="actions"
        form-id="kpiIndiDef"
        :data-url="dataurl"
        show-selection
        :modal-props="{ class: 'noBottom' }"
        :search-fields="['indiName']"
        :show-advance-query="true"
        :process-res="processRes"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="islink" slot-scope="text, record">
          <a :title="text" @click="rowClick(record)">{{ text }}</a>
        </div>
        <div slot="dataPeriod" slot-scope="text, record">
          <span :title="record.year + '年' + record.dataPeriod">{{
            record.year + '年' + record.dataPeriod
          }}</span>
        </div>
        <div slot="indiVal" slot-scope="text, record">
          <div v-if="record.indiVal === 'null'"></div>
          <span v-else :title="record.indiVal">{{ record.indiVal }}</span>
        </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>

          <!-- <a :title="text" @click="rowClick(record)">{{ text }}</a> -->
        </div>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import auditAdvancedImport from '../../components/audit-advanced-import.vue'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import KpiService from '../kpi-service'
import components from './_import-components/kpi-monitor-list-import'

export default {
  name: 'KpiMonitorList',
  metaInfo() {
    return {
      title: this.title,
    }
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      catvisible: false,
      treeparams: {
        configId: 101,
      },
      searchform: 'searchform',
      expressions: [],
      formData: {
        indiName: '',
        busiClass: '',
        alertStatus: '',
        indiFrequency: '',
        monitorRange: '',
        monitorDept: '',
      },
      optionsArray: {
        optionsFrequency: [], // 指标时间维度下拉选项
        optionsStatus: [], // 指标状态下拉选项
        optionsRange: [], // 监测范围
      },
      dataurl: '',
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '业务分类',
          dataIndex: 'busiClass',
          width: '150px',
        },
        {
          title: '指标名称',
          dataIndex: 'indiName',
          width: '150px',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '指标时间维度',
          dataIndex: 'indiFrequency',
        },
        {
          title: '监测范围',
          dataIndex: 'monitorRange',
        },
        {
          title: '监测单位',
          dataIndex: 'monitorDeptStr',
        },
        {
          title: '数据时点',
          dataIndex: 'dataPeriod',
          scopedSlots: { customRender: 'dataPeriod' },
        },
        {
          title: '预警状态',
          dataIndex: 'alertStatus',
          scopedSlots: { customRender: 'alertStatus' },
        },
        {
          title: '指标值',
          dataIndex: 'indiVal',
          scopedSlots: { customRender: 'indiVal' },
        },
        {
          title: '指标值单位',
          dataIndex: 'indiUnit',
        },
        {
          title: '操作',
          dataIndex: 'opt',
          customRender: (text, record, index) => {
            return (
              <span>
                <a vOn:click={(evt) => this.isNotfileBtn(record.id, 'qsfx')}>趋势分析</a>
                <br />
                <a vOn:click={(evt) => this.isNotfileBtn(record, 'dupont')}>杜邦分析</a>
                <br />
                <a vOn:click={(evt) => this.isNotfileBtn(record.id, 'cklsz')}>查看历史值</a>
              </span>
            )
          },
        },
      ],
      actions: [
        {
          label: '更新计算指标值',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: 'kpiIndiDef-create', // 权限控制
          callback: () => {
            this.refreshJszb()
            // const url = '/kpi-indi-form' // 新页面要打开的路由地址
            // crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            //   if (refreshFlag) {
            //     // 这里写或者调刷新的方法
            //     this.refresh()
            //   }
            // })
          },
        },
        {
          label: '下发预警单',
          id: 'xiafa',
          permission: null,
          callback: () => {
            this.fnxfyjd()
          },
        },
        // {
        //   label: '导入',
        //   id: 'import',
        //   permission: null,
        //   callback: () => {
        //     alert('xiafaaaaa')
        //   },
        // },
        // {
        //   label: '导出',
        //   id: 'export',
        //   permission: null,
        //   callback: () => {
        //     alert('xiafaaaaa')
        //   },
        // },
      ],
      history: false,
      recordId: '',
      title: '指标监测列表',
      yclist: false,
      startTime: null,
    }
  },
  mounted() {
    // 获取数据字典-状态
    this.getDictionary('ALERT_STATUS', 'optionsStatus')
    // 获取数据字典-指标时间维度
    this.getDictionary('KPI_FREQUENCY', 'optionsFrequency')
    // 获取数据字典-监测范围
    this.getDictionary('MONITOR_RANGE', 'optionsRange')
  },
  created() {
    if (this.$route.query.history === '1') {
      this.history = true
      this.recordId = this.$route.query.id
    } else if (this.$route.query.yc === '1') {
      this.yclist = true
      this.recordId = this.$route.query.id
    }
    if (this.history) {
      this.actions = [
        // {
        //   label: '导出',
        //   id: 'export',
        //   permission: null,
        //   callback: () => {
        //     alert('xiafaaaaa')
        //   },
        // },
      ]
      this.columns.splice(10, 1)
      this.dataurl = 'api/xcoa-mobile/v1/kpiindimonitor/getHistoryIndiVal'
      this.title = '历史指标监测列表'
      this.expressions.push({
        dataType: 'str',
        name: 'id',
        op: 'eq',
        stringValue: `${this.recordId}`,
      })
    } else if (this.yclist) {
      this.actions = [
        {
          label: '下发预警单',
          id: 'xiafa',
          permission: null,
          callback: () => {
            this.fnxfyjd()
          },
        },
      ]
      this.columns = [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '业务分类',
          dataIndex: 'busiClass',
          width: '150px',
        },
        {
          title: '指标名称',
          dataIndex: 'indiName',
          width: '150px',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '指标时间维度',
          dataIndex: 'indiFrequency',
        },
        {
          title: '监测单位',
          dataIndex: 'monitorDeptStr',
        },
        {
          title: '数据时期',
          dataIndex: 'dataPeriod',
          scopedSlots: { customRender: 'dataPeriod' },
        },
        {
          title: '指标值',
          dataIndex: 'indiVal',
        },
        {
          title: '指标值单位',
          dataIndex: 'indiUnit',
        },
        {
          title: '预警状态',
          dataIndex: 'alertStatus',
          scopedSlots: { customRender: 'alertStatus' },
        },
        {
          title: '操作',
          dataIndex: 'opt',
          customRender: (text, record, index) => {
            return (
              <span>
                <a vOn:click={(evt) => this.isNotfileBtn(record.id, 'qsfx')}>趋势分析</a>
                <br />
                <a vOn:click={(evt) => this.isNotfileBtn(record, 'dupont')}>杜邦分析</a>
              </span>
            )
          },
        },
      ]
      this.dataurl = 'api/xcoa-mobile/v1/kpiindimonitor/getAbnormalIndiVal'
      this.title = '异常指标监测列表'
      this.startTime = new Date(new Date().getFullYear() - 1 + '-01-01 00:00:00').getTime()
      this.expressions.push({
        dataType: 'long',
        name: 'creationTime',
        op: 'ge',
        longValue: `${this.startTime}`,
      })
    } else {
      this.dataurl = 'api/xcoa-mobile/v1/kpiindimonitor/list'
    }
  },
  methods: {
    refreshJszb() {
      const selectRows = this.$refs.dataTable.getSelectedRows()
      const selectedRowKeys = []
      selectRows.forEach((i) => {
        if (i && i.dataFrom === 'system') {
          selectedRowKeys.push(i.id)
        }
      })
      if (selectedRowKeys.length === 0) {
        if (selectRows.length > 0) {
          Modal.warning({
            title: '提示',
            content: '您选择的指标数据来源不是系统集成，请选择需要更新系统集成计算的指标!',
          })
        } else {
          Modal.warning({
            title: '提示',
            content: '请选择需要更新系统计算的指标!',
          })
        }
        return false
      }
      return KpiService.getResetIndiResult(selectedRowKeys.join(',')).then((res) => {
        if (res) {
          message.info('更新成功', 1)
          this.refresh()
          this.$refs.dataTable.clearSelection()
        } else {
          Modal.warning({
            title: '提示',
            content: '更新失败，请联系管理员',
          })
        }
      })
    },
    fnxfyjd() {
      const selectedRowKeys = this.$refs.dataTable.getSelectedRowKeys()

      if (selectedRowKeys.length === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择下发预警的指标!',
        })
        return false
      }
      const zclist = []
      const list = this.$refs.dataTable.getSelectedRows()
      list.forEach((l) => {
        if (
          l.alertStatus === 'C' ||
          l.alertStatus === 'D' ||
          l.alertStatus === '' ||
          l.alertStatus === null ||
          l.alertStatus === undefined
        ) {
          zclist.push(l)
        }
      })
      if (zclist.length > 0) {
        Modal.warning({
          title: '提示',
          content: '请去掉下发预警的非异常指标!',
        })
        return false
      }
      const url = '/sd-flow-guide?code=PRODUCT_KPI_ORDER&zbid=' + selectedRowKeys.join(',') // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refresh()
        }
      })
    },
    isNotfileBtn(record, type) {
      let url = ''
      if (type === 'qsfx') {
        url = '/sd-frame/kpi-trend-analysis?id=' + record
        crossWindowWatcher.waitForChanged(url)
      } else if (type === 'cklsz') {
        url = '/sd-frame/kpi-monitor-list?id=' + record + '&history=1'
        crossWindowWatcher.waitForChanged(url)
      } else if (type === 'dupont') {
        url =
          '/sd-frame/kpi-du-pont-analysis?id=' +
          record.id +
          '&title=' +
          record.monitorDeptStr +
          (record.indiName ? record.indiName : record.indiNameChildren) +
          record.year +
          '年' +
          record.dataPeriod +
          '的杜邦分析'
        crossWindowWatcher.waitForChanged(url)
      }
    },
    // 数据返回后，整理response对象
    processRes(res) {
      if (this.history || this.yclist) {
        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 ? item.alertStatus.split(',') : []
              const indiUnit = item.indiUnit.split(',')
              const indiVal = item.indiVal.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] ? alertStatus[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] ? alertStatus[mindex] : ''
                  item.indiVal = indiVal[mindex]
                  item.indiUnit = indiUnit[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
            }
          })
        }
      } else {
        if (res.data) {
          res.data.forEach((item) => {
            // 判断监测单位是否有下级节点
            if (item.monitorDeptNameStrs[0]) {
              // 如果只有子级，则首级监测单位报送部门显示为空
              if (item.monitorDeptNameStrs.indexOf(',') === -1) {
                item.monitorDeptStr = item.monitorDeptNameStrs // 监测单位
              } else {
                item.children = []
                const monitorDepts = item.monitorDeptNameStrs.split(',')
                const monitorDeptsid = item.monitorDeptIdStrs.split(',')
                const alertStatus = item.alertStatus ? item.alertStatus.split(',') : []
                const indiUnit = item.indiUnit.split(',')
                const indiVal = item.indiVal.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) {
                    // 子级
                    item.children.push({
                      id: ids[mindex],
                      monitorDeptStr: mitem,
                      alertStatus: alertStatus[mindex] ? alertStatus[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] ? alertStatus[mindex] : ''
                    item.indiVal = indiVal[mindex]
                    item.indiUnit = indiUnit[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]
                  }
                })
              }
            }
          })
        }
      }
      return res
    },
    mapCategoryItems(items) {
      return (items || []).map((item) => {
        const result = {
          id: item.id,
          name: item.text,
          // checkable: true,
          isLeaf: item.leaf,
          checkable: !item.expandable,
        }
        return result
      })
    },
    // 获取用于选择的业务类型分类树
    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: '应用类型获取失败' })
        })
    },
    // 获取数据字典
    getDictionary(id, fieldName) {
      return KpiService.getDictionary(id)
        .then((res) => {
          if (res[0]) {
            res.forEach((item) => {
              this.optionsArray[fieldName].push({
                label: item.name,
                value: item.id,
              })
            })
          }
        })
        .catch((e) => {
          message.error({ content: '数据字典获取失败' })
        })
    },
    // 开关点击事件
    switchClick(record) {},
    clearSelection() {
      this.$refs.sjzlTable.clearSelection()
    },
    // 刷新列表
    refresh() {
      this.$refs.dataTable.refresh()
    },
    // 新建、详情打开新页面
    rowClick(record) {
      const url = '/kpi-indi-form?record=' + record.indiId // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    // 重置查询
    resetForm() {
      this.expressions = []
      this.formData = {}
    },
    // 查询
    handleSearch() {
      this.expressions = []
      if (this.history) {
        this.expressions.push({
          dataType: 'str',
          name: 'id',
          op: 'eq',
          stringValue: `${this.recordId}`,
        })
      } else if (this.yclist) {
        this.expressions.push({
          dataType: 'long',
          name: 'creationTime',
          op: 'ge',
          longValue: `${this.startTime}`,
        })
      }
      // 业务分类
      if (this.formData.busiClass[0]) {
        this.expressions.push({
          dataType: 'str',
          name: 'busiClass',
          op: 'eq',
          stringValue: `${this.formData.busiClass[0].name}`,
        })
      }
      // 指标名称
      if (this.formData.indiName) {
        this.expressions.push({
          dataType: 'str',
          name: 'indiName',
          op: 'like',
          stringValue: `${this.formData.indiName}`,
        })
      }
      // 指标时间维度
      if (this.formData.indiFrequency) {
        this.expressions.push({
          dataType: 'str',
          name: 'indiFrequency',
          op: 'eq',
          stringValue: `${this.formData.indiFrequency}`,
        })
      }
      // 监测范围
      if (this.formData.monitorRange) {
        this.expressions.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.expressions.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;
  }
}
.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>
