<template>
  <span>
    <audit-form-top-banner
      :handel-save-form="saveForm"
      :form-data="mode"
      @handelSaveForm="saveForm"
    >
      <sd-detail-form
        ref="docform"
        form-id="kpiIndiGroup"
        page-id="kpi/group/kpiIndiGroup"
        :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
        :class="$style.form"
        @close="close(true)"
        @saved="saved"
      >
        <template v-slot="{ model, fields }">
          <table>
            <tr>
              <td style="border: none">
                <audit-advanced-group
                  :expand="expand"
                  expand-str="expand"
                  :group-label="'基本信息'"
                  tablestyle="''"
                  @changedClick="changedClick"
                ></audit-advanced-group>
              </td>
            </tr>
          </table>

          <table v-show="expand">
            <colgroup>
              <col style="width: 185px;" /><col /> <col style="width: 185px;" /><col />
            </colgroup>
            <tr>
              <!-- 指标组名称 -->
              <sd-form-item-td name="groupName" />
              <!-- ID -->
              <sd-form-item-td name="id" :hidden="true" />
              <!-- 指标组编号 -->
              <sd-form-item-td name="groupNo">
                <a-form-model-item
                  :rules="[
                    {
                      pattern: '^[A-Za-z0-9-_]+$',
                      message: '只能包含英文字母、数字、下横线，请重新输入',
                      trigger: 'change',
                    },
                    { validator: handleGroupNo },
                  ]"
                  prop="groupNo"
                >
                  <a-input v-model="model.groupNo"></a-input>
                </a-form-model-item>
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 指标组状态 -->
              <sd-form-item-td name="groupStatus" />
              <!-- 业务分类 -->
              <sd-form-item-td name="busiClass">
                <sd-tree-picker
                  v-model="model.busiClass"
                  single
                  :load-tree-data="loadTreeDataBusi"
                  a-select
                  @change="busiChange"
                >
                </sd-tree-picker>
              </sd-form-item-td>
              <!-- 业务分类名称 -->
              <sd-form-item-td name="busiClassName" :hidden="true" />
              <!-- 业务分类ID -->
              <sd-form-item-td name="busiClassId" :hidden="true" />
            </tr>
            <tr>
              <!-- 指标组维度 -->
              <sd-form-item-td name="groupFrequency"> </sd-form-item-td>
              <!-- 指标组计算规则 -->
              <sd-form-item-td name="groupCalRule"> </sd-form-item-td>
            </tr>
            <tr>
              <!-- 规则描述 -->
              <sd-form-item-td name="ruleDesc" :colspan="3">
                <template v-slot:read-and-edit="{ editable }">
                  <a-textarea
                    v-model="model.ruleDesc"
                    :auto-size="{ maxRows: 3, minRows: 3 }"
                  ></a-textarea>
                </template>
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 监测范围 -->
              <sd-form-item-td name="monitorRange" component="a-radio-group" />
              <!-- 监测单位 -->
              <sd-form-item-td name="monitorDeptMember" @change="deptChange" />
              <!-- 监测单位ID -->
              <sd-form-item-td name="monitorDeptId" :hidden="true" />
              <!-- 监测单位code -->
              <sd-form-item-td name="monitorDeptCode" :hidden="true" />
              <!-- 监测单位Name -->
              <sd-form-item-td name="monitorDeptName" :hidden="true" />
            </tr>
            <tr>
              <!-- 创建人员 -->
              <sd-form-item-td name="creatorName" label="维护人员" />
              <!-- 创建单位 -->
              <sd-form-item-td name="createDeptName" label="维护单位" />
            </tr>
            <tr>
              <!-- 创建日期 -->
              <sd-form-item-td name="creationTime" :colspan="3" label="维护日期" />
            </tr>
          </table>

          <table>
            <tr :class="$style.childTableTr">
              <!-- 指标列表 -->
              <sd-form-item-td name="kpiIndiGroupDetailList" :label="null" :colspan="4">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="indiExpand"
                    expand-str="indiExpand"
                    group-label="指标列表"
                    @changedClick="changedClick"
                  >
                    <template>
                      <div v-show="indiExpand && editable" :class="$style.btnselect">
                        <a-button type="link" :class="$style.batchselect" @click="showSelectName">
                          <a-icon type="check-circle" :theme="'filled'" />
                          选择
                        </a-button>
                      </div>
                      <kpi-indicator-group-child-table
                        :key="childTableKey"
                        ref="orderTable"
                        v-model="model.kpiIndiGroupDetailList"
                        :class="$style.orderChild"
                        :edit-row="editRow"
                        :label="null"
                        :read-only="false"
                        :addbuttonvisiable="false"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                            },
                          ].concat(Array.from(fields.kpiIndiGroupDetailList.attr.dync))
                        "
                        :columns="indiColumns"
                      >
                        <!-- 指标名称 -->
                        <template v-slot:indiName="{ field, text, record }">
                          <a :title="text" @click="rowClick($event, record)">{{ text }}</a>
                        </template>
                        <!-- 指标值单位 -->
                        <template v-slot:indiUnit="{ field, text, record }">
                          {{ getDictValue(indiUnitDict, text) }}
                        </template>
                        <!-- 指标状态 -->
                        <template v-slot:indiStatus="{ field, text, record }">
                          {{ text }}
                        </template>
                        <!-- 指标时间维度 -->
                        <template v-slot:indiFrequency="{ field, text, record }">
                          {{ text }}
                        </template>
                        <!-- 监测范围 -->
                        <template v-slot:monitorRange="{ field, text, record }">
                          {{ text }}
                        </template>
                      </kpi-indicator-group-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item-td>
            </tr>
          </table>
        </template>
      </sd-detail-form>
    </audit-form-top-banner>

    <!-- 指标选择器 -->
    <kpi-analysis-select-modal
      :visible="visible"
      :select-expressions="[
        {
          dataType: 'str',
          name: 'indiStatus',
          op: 'eq',
          stringValue: '1',
        },
      ]"
      @handleCancel="handleCancel"
      @handleOk="handleOk"
    />
  </span>
</template>

<script>
import { message } from '@/common/one-ui'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditFormTopBanner from '@product/iam/components/audit-form-top-banner'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import kpiAnalysisSelectModal from '../analysis/kpi-analysis-select-modal.vue'
import KpiService from '../kpi-service'
import kpiIndicatorGroupChildTable from './kpi-indicator-group-child-table.vue'
import kpiIndicatorGroupService from './kpi-indicator-group-service'
import components from './_import-components/kpi-indicator-group-form-import'

export default {
  name: 'KpiIndicatorGroupForm',
  metaInfo: {
    title: '指标组定义',
  },
  components: {
    auditFormTopBanner,
    kpiIndicatorGroupChildTable,
    kpiAnalysisSelectModal,
    auditAdvancedGroup,
    ...components,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      treeparams: {
        // 业务分类树
        configId: 101,
      },
      mode: 'EDIT',
      childTableKey: 0,
      indiUnitDict: [], // 指标值单位字典
      editRow: false,
      visible: false,
      expand: true,
      indiExpand: true,
      indiColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'sortNo', sdHidden: true },
        { dataIndex: 'groupId', sdHidden: true },
        { dataIndex: 'indiId', sdHidden: true },
        {
          title: '指标名称',
          dataIndex: 'indiName',
        },
        { title: '指标值单位', dataIndex: 'indiUnit' },
        {
          title: '指标编号',
          dataIndex: 'indiNo',
        },
        {
          title: '指标状态',
          dataIndex: 'indiStatus',
        },
        {
          title: '指标时间维度',
          dataIndex: 'indiFrequency',
        },
        {
          title: '监测范围',
          dataIndex: 'monitorRange',
        },
      ],
    }
  },
  created() {
    // 获取指标值单位
    kpiIndicatorGroupService.getDictValue('INDI_UNIT').then((res) => {
      this.indiUnitDict = res.data
    })
  },
  methods: {
    loadTreeDataBusi(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
      })
    },
    busiChange(val) {
      // 业务分类id及名称赋值
      if (val && val[0]) {
        this.$refs.docform.setFieldValue('busiClassId', val[0].id)
        this.$refs.docform.setFieldValue('busiClassName', val[0].name)
      } else {
        this.$refs.docform.setFieldValue('busiClassId')
        this.$refs.docform.setFieldValue('busiClassName')
      }
    },
    handleGroupNo(rule, value, callback) {
      const id = this.$refs.docform.getFieldValue('id')
      // 编号重复校验
      kpiIndicatorGroupService
        .hasGroupNo(id, value)
        .then((res) => {
          if (res) {
            callback(new Error('编号重复，请重新输入'))
          } else {
            callback()
          }
        })
        .catch(() => {
          message.error('出错了，请联系管理员', 1)
          callback(new Error('编号校验出错，请联系管理员'))
        })
    },
    saved() {
      this.close(true)
    },
    // 保存
    saveForm() {
      this.$refs.docform.validateFields().then(() => {
        message.success('保存成功').then(() => {
          this.$refs.docform.saveBtnClick()
        })
      })
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    rowClick(e, record) {
      const url = '/kpi-indi-form?record=' + record.indiId + '&mode=view' // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url)
      e.stopPropagation()
    },

    // 显示选择指标列表
    showSelectName(e) {
      this.visible = true
    },
    // 指标选择确认
    handleOk(rows) {
      const selectData = []
      rows.forEach((item) => {
        item.indiId = item.id
        item.id = null
        selectData.push(item)
      })
      this.$refs.docform.setFieldValue('kpiIndiGroupDetailList', selectData)
      this.handleCancel()
    },
    // 异常指标选择取消
    handleCancel(event) {
      this.visible = false
    },
    // 获取指标值单位
    getDictValue(dictData, val) {
      return dictData.find((item) => {
        return item.id === val
      })?.name
    },
    // 监测单位变化时
    deptChange(val) {
      // 监测单位ID
      this.$refs.docform.setFieldValue('monitorDeptId', val.map((item) => item.id).join(','))
      // 监测单位code
      this.$refs.docform.setFieldValue('monitorDeptCode', val.map((item) => item.code).join(','))

      // 监测单位Name
      this.$refs.docform.setFieldValue('monitorDeptName', val.map((item) => item.name).join(','))
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';
.form {
  :global(.ant-calendar-picker) {
    width: 100%;
  }
}
.btnselect {
  position: relative;
  top: -1px;
  right: 100px;
  float: right;
  .batchselect {
    z-index: 100;
    margin-left: 10px;
  }
}
.child-table-tr {
  td:first-child {
    padding: 0 !important;
  }
}
</style>
