<template>
  <div :class="$style.indiList">
    <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="'业务分类'" 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="indiStatus">
              <a-select v-model="formData.indiStatus" :options="optionsArray.optionsStatus" />
            </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="'监测单位'" prop="monitorDept">
              <sd-group-picker v-model="formData.monitorDept" :read-only="false" />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>

      <!-- 列表组件 -->
      <sd-data-table
        ref="dataTable"
        :class="$style.dataTable"
        :row-key="'id'"
        :filter-expressions="expressions"
        :columns="columns"
        :actions="actions"
        form-id="kpiIndiDef"
        :data-url="dataurl"
        :show-selection="
          (record) => {
            // 只有主单位行有复选框
            return !record.isChildren
          }
        "
        :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>
      </sd-data-table>
      <!-- 下发报送 -->
      <kpi-sendtask-form :visible="visible" :indi-info="indiInfo"></kpi-sendtask-form>
    </a-card>
  </div>
</template>

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

export default {
  name: 'KpiIndiList',
  metaInfo: {
    title: '指标定义列表',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    kpiSendtaskForm,
  },

  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      visible: false,
      indiInfo: {}, // 下发指标信息
      catvisible: false,
      treeparams: {
        configId: 101,
      },
      searchform: 'searchform',
      expressions: [],
      formData: {
        indiName: '',
        busiClass: '',
        indiStatus: '',
        indiFrequency: '',
        monitorRange: '',
        monitorDept: '',
      },
      optionsArray: {
        optionsFrequency: [], // 指标时间维度下拉选项
        optionsStatus: [], // 指标状态下拉选项
        optionsRange: [], // 监测范围
      },
      dataurl: 'api/xcoa-mobile/v1/kpi-indi-def/list',
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '业务分类',
          dataIndex: 'busiClassName',
          width: '150px',
        },
        {
          title: '指标名称',
          dataIndex: 'indiName',
          width: '150px',
          scopedSlots: { customRender: 'islink' },
        },

        {
          title: '指标编号',
          dataIndex: 'indiNo',
        },
        {
          title: '指标状态',
          dataIndex: 'indiStatus',
        },
        {
          title: '指标时间维度',
          dataIndex: 'indiFrequency',
        },
        {
          title: '监测范围',
          dataIndex: 'monitorRange',
        },
        {
          title: '监测单位',
          dataIndex: 'monitorDeptStr',
        },
        {
          title: '报送部门',
          dataIndex: 'submitterDeptStr',
        },
        {
          title: '是否本单位',
          dataIndex: 'izSelfStr',
          sdHidden: true,
        },
      ],
      actions: [
        {
          label: '删除',
          id: 'delete',
          permission: 'kpiIndiDef-delete',
          type: TableActionTypes.batch,
          callback: (keys) => {
            this.deleteRows(keys)
          },
        },
        {
          label: '新建',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: 'kpiIndiDef-create', // 权限控制
          callback: () => {
            const url = '/kpi-indi-form' // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refresh()
              }
            })
          },
        },
        {
          label: '下发报送任务',
          id: 'sendtask',
          permission: null,
          callback: () => {
            const selectrow = this.$refs.dataTable.getSelectedRows()
            if (selectrow.length === 1) {
              this.indiInfo = selectrow[0]
              this.visible = true
            } else {
              alert('请选择一条数据进行下发')
            }
          },
        },
      ],
    }
  },
  mounted() {
    // 获取数据字典-状态
    this.getDictionary('STATUS', 'optionsStatus')
    // 获取数据字典-指标时间维度
    this.getDictionary('KPI_FREQUENCY', 'optionsFrequency')
    // 获取数据字典-监测范围
    this.getDictionary('MONITOR_RANGE', 'optionsRange')
  },
  methods: {
    // 数据返回后，整理response对象
    processRes(res) {
      if (res.data) {
        res.data.forEach((item) => {
          // 判断监测单位是否有下级节点
          if (item.monitorDepts[0]) {
            item.children = []
            // 如果只有子级，则首级监测单位报送部门显示为空
            if (item.izSelfStr.indexOf('1') === -1) {
              item.monitorDeptStr = '' // 监测单位
              item.submitterDeptStr = '' // 报送部门
            }
            // 循环监测单位
            item.monitorDepts.forEach((mitem, mindex) => {
              if (mitem.izSelf === '0') {
                // 子级
                item.children.push({
                  id: item.id + '_' + mindex + 1,
                  monitorDeptStr: mitem.monitorDeptName,
                  submitterDeptStr: item.submitterDepts[mindex].submitterDeptName,
                  isChildren: true,
                })
              } else {
                // 首级
                item.monitorDeptStr = mitem.monitorDeptName // 监测单位
                item.submitterDeptStr = item.submitterDepts[mindex].submitterDeptName // 报送部门
              }
            })
          }
        })
      }
      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.id // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    // 重置查询
    resetForm() {
      this.expressions = []
      this.formData = {}
    },
    // 查询
    handleSearch() {
      this.expressions = []
      // 业务分类
      if (this.formData.busiClass[0]) {
        this.expressions.push({
          dataType: 'str',
          name: 'busiClassName',
          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.indiStatus) {
        this.expressions.push({
          dataType: 'str',
          name: 'indiStatus',
          op: 'eq',
          stringValue: `${this.formData.indiStatus}`,
        })
      }
      // 指标时间维度
      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}`,
        })
      }
    },
    // 删除数据
    deleteRows(selectedRowKeys) {
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          cancelText: '取消',
          okType: 'danger',
          onOk: () => {
            axios({
              url: 'api/framework/v1/page/kpiIndiDef',
              method: 'delete',
              params: {
                ids: selectedRowKeys.join(','),
              },
            })
              .then(() => {
                this.$refs.dataTable.clearSelection()
                this.$refs.dataTable.refresh()
                message.success('删除成功')
              })
              .finally(resolve)
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.indi-list {
  .tree-select {
    :global .ant-select {
      padding: 0;
    }
  }
  .data-table {
    :global .ant-checkbox-wrapper-disabled {
      display: none;
    }
  }
}
</style>
