<template>
  <a-card>
    <div :class="$style.wrapHeight">
      <!-- 高级搜索组件 -->
      <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="'\u2003业务分类'" 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="'\u2003\u2003指标组名称'" prop="groupName">
              <a-input v-model="formData.groupName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'指标组状态'" prop="groupStatus">
              <a-select v-model="formData.groupStatus" :options="optionsArray.optionsStatus" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'指标组时间维度'" prop="groupFrequency">
              <a-select
                v-model="formData.groupFrequency"
                :options="optionsArray.optionsFrequency"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'\u2003监测范围'" 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="'\u2003\u2003\u2003监测单位'" 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-ex
        ref="kpiIndicatorGroupTable"
        form-id="kpiIndiGroup"
        page-id="kpi/group/kpiIndiGroup"
        data-url="api/xcoa-mobile/v1/kpiindigroup/all-list"
        :columns="columns"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :filter-expressions="expressions"
        :search-fields="['groupName']"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a @click="open(record)">{{ text }}</a>
        </template>
        <template slot="groupStatus" slot-scope="text, record">
          {{ getFieldValue(optionsArray.optionsStatus, text) }}
        </template>
        <template slot="groupCalRule" slot-scope="text, record">
          {{ getFieldValue(optionsArray.optionsRule, text) }}
        </template>
        <template slot="groupFrequency" slot-scope="text, record">
          {{ getFieldValue(optionsArray.optionsFrequency, text) }}
        </template>
        <template slot="monitorRange" slot-scope="text, record">
          {{ getFieldValue(optionsArray.optionsRange, text) }}
        </template>
      </sd-data-table-ex>
    </div>
  </a-card>
</template>

<script>
import { message } from 'ant-design-vue'
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 KpiService from '../kpi-service'
import kpiIndicatorGroupService from './kpi-indicator-group-service'
import components from './_import-components/kpi-indicator-group-list-import'

export default {
  name: 'KpiIndicatorGroupList',
  metaInfo: {
    title: '指标组定义',
  },
  components: {
    auditAdvancedQuery,
    ...components,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        { dataIndex: 'id', sdHidden: true },
        {
          title: '业务分类',
          dataIndex: 'busiClassName',
          sorter: true,
        },
        {
          title: '指标组名称',
          dataIndex: 'groupName',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '指标组编号',
          dataIndex: 'groupNo',
          width: '150px',
          defaultSortOrder: 'ascend',
        },
        {
          title: '指标组状态',
          dataIndex: 'groupStatus',
          width: '150px',
          scopedSlots: { customRender: 'groupStatus' },
        },
        {
          title: '指标组计算规则',
          dataIndex: 'groupCalRule',
          scopedSlots: { customRender: 'groupCalRule' },
        },
        {
          title: '指标组时间维度',
          dataIndex: 'groupFrequency',
          scopedSlots: { customRender: 'groupFrequency' },
          sorter: true,
        },
        {
          title: '监测范围',
          dataIndex: 'monitorRange',
          scopedSlots: { customRender: 'monitorRange' },
        },
        {
          title: '监测单位',
          dataIndex: 'monitorDeptName',
        },
      ],
      actions: [
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: 'delete',
        },
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null, // 权限控制
          callback: () => {
            const url = '/kpi-indicator-group-form' // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refresh()
              }
            })
          },
        },
      ],
      radioType: false,
      radioValue: '0',
      expressions: [],
      formData: {
        groupName: '',
        busiClass: '',
        groupStatus: '',
        groupFrequency: '',
        monitorRange: '',
        monitorDept: [],
      },
      optionsArray: {
        optionsFrequency: [], // 指标时间维度下拉选项
        optionsStatus: [], // 指标状态下拉选项
        optionsRange: [], // 监测范围
        optionsRule: [], // 计算规则
      },
      treeparams: {
        configId: 101,
      },
    }
  },
  created() {},
  mounted() {
    // 获取数据字典-状态
    this.getDictionary('GROUP_STATUS', 'optionsStatus')
    // 获取数据字典-指标时间维度
    this.getDictionary('KPI_FREQUENCY', 'optionsFrequency')
    // 获取数据字典-监测范围
    this.getDictionary('MONITOR_RANGE', 'optionsRange')
    // 获取数据字典-计算规则
    this.getDictionary('GROUP_CAL_RULE', 'optionsRule')
  },
  methods: {
    // 获取列值
    getFieldValue(dict, val) {
      if (dict.length === 0) return ''
      return dict.find((item) => {
        return item.value === val
      }).label
    },
    // 获取数据字典
    getDictionary(id, fieldName) {
      return kpiIndicatorGroupService
        .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: '数据字典获取失败' })
        })
    },
    open(record) {
      const url = `/kpi-indicator-group-form?record=` + record.id
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refresh()
        }
      })
    },
    // 刷新表格
    refresh() {
      this.$refs.kpiIndicatorGroupTable.refresh()
    },
    // 重置查询
    resetForm() {
      this.expressions = []
      this.formData = {}
    },
    // 查询
    handleSearch() {
      this.expressions = []
      // 业务分类
      if (this.formData.busiClass[0]) {
        this.expressions.push({
          dataType: 'str',
          name: 'busiClassName',
          op: 'like',
          stringValue: `${this.formData.busiClass[0].name}`,
        })
      }
      // 指标名称
      if (this.formData.groupName) {
        this.expressions.push({
          dataType: 'str',
          name: 'groupName',
          op: 'like',
          stringValue: `%${this.formData.groupName}%`,
        })
      }
      // 指标状态
      if (this.formData.groupStatus) {
        this.expressions.push({
          dataType: 'str',
          name: 'groupStatus',
          op: 'like',
          stringValue: `${this.formData.groupStatus}`,
        })
      }
      // 指标时间维度
      if (this.formData.groupFrequency) {
        this.expressions.push({
          dataType: 'str',
          name: 'groupFrequency',
          op: 'like',
          stringValue: `${this.formData.groupFrequency}`,
        })
      }
      // 监测范围
      if (this.formData.monitorRange) {
        this.expressions.push({
          dataType: 'str',
          name: 'monitorRange',
          op: 'like',
          stringValue: `${this.formData.monitorRange}`,
        })
      }
      // 监测单位
      if (this.formData.monitorDept[0]) {
        let deptCodes = ''
        this.formData.monitorDept.forEach((item) => {
          if (deptCodes === '') {
            deptCodes = item.code
          } else {
            deptCodes = deptCodes + ',' + item.code
          }
        })
        this.expressions.push({
          dataType: 'str',
          name: 'monitorDeptCode',
          op: 'in',
          stringValue: `${deptCodes}`,
        })
      }
    },
    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: '应用类型获取失败' })
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.tree-select {
  :global .ant-select {
    padding: 0;
  }
}
.btns {
  position: absolute;
  top: 20px;
  right: 0;
  left: 20px;
  z-index: 100;
  width: calc(100% - 400px);
  span {
    color: blue;
  }
}
.wrap-height {
  :global(.searchdiv_audit-advanced-query_product) {
    :global(.searchform_audit-advanced-query_product) {
      :global(.ant-form-item-control-wrapper) {
        width: calc(100% - 160px);
      }
    }
  }
}
</style>
