<template>
  <audit-form-top-banner :handel-save-form="saveForm" :form-data="mode" @handelSaveForm="saveForm">
    <sd-detail-form
      ref="kpiIndiForm"
      form-id="kpiIndiDef"
      page-id="kpi/def/definition/kpiIndiDef"
      :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
      :class="[$style.form, { [$style.readOnlyForm]: mode === 'VIEW' }]"
      :read-only="mode === 'VIEW'"
      @close="close(true)"
      @saved="saved"
      @sdFormReady="sdFormReady"
    >
      <template v-slot="{ model, fields }">
        <table>
          <tr>
            <td style="padding-left:5px;border:none">
              <audit-advanced-group
                :expand="basicExpand"
                :expand-str="'basicExpand'"
                :group-label="'基本信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-show="basicExpand">
          <tr>
            <td class="ant-form-item-label ant-form-item-label" :class="$style.firstTd"></td>
            <td class="ant-form-item-control-wrapper" :class="$style.firstTd"></td>
            <td class="ant-form-item-label ant-form-item-label" :class="$style.firstTd"></td>
            <td class="ant-form-item-control-wrapper" :class="$style.firstTd"></td>
            <sd-form-item-td name="id" label="ID" :colspan="3" :hidden="true"> </sd-form-item-td>
          </tr>
          <tr>
            <!-- 指标名称 -->
            <sd-form-item-td name="indiName" label="指标名称"> </sd-form-item-td>
            <!-- 指标编号 -->
            <sd-form-item-td name="indiNo" label="指标编号">
              <a-form-model-item
                :rules="[
                  {
                    pattern: '^[A-Za-z0-9-_]+$',
                    message: '只能包含英文字母、数字、下横线，请重新输入',
                    trigger: 'change',
                  },
                  { validator: handleIndiNo },
                ]"
                prop="indiNo"
              >
                <a-input v-model="model.indiNo"></a-input>
              </a-form-model-item>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 指标状态 -->
            <sd-form-item-td name="indiStatus" label="指标状态"> </sd-form-item-td>
            <!-- 指标值单位 -->
            <sd-form-item-td name="indiUnit" label="指标值单位"> </sd-form-item-td>
          </tr>
          <tr>
            <!-- 指标时间维度--新建时可编辑，保存后只可查看不可编辑 -->
            <td v-if="!!model.id" class="ant-form-item-label">
              <label>指标时间维度</label>
            </td>
            <td v-if="!!model.id" class="ant-form-item-control-wrapper">
              <span v-if="model.indiFrequency === '1'">日</span>
              <span v-if="model.indiFrequency === '2'">周</span>
              <span v-if="model.indiFrequency === '3'">月</span>
              <span v-if="model.indiFrequency === '4'">季度</span>
              <span v-if="model.indiFrequency === '5'">半年</span>
              <span v-if="model.indiFrequency === '6'">年</span>
            </td>
            <sd-form-item-td
              v-else
              name="indiFrequency"
              label="指标时间维度"
              component="a-radio-group"
            >
            </sd-form-item-td>
            <!-- 指标性质 -->
            <sd-form-item-td name="indiAttr" label="指标性质"> </sd-form-item-td>
          </tr>
          <tr>
            <!-- 业务分类 -->
            <sd-form-item-td name="busiClass" label="业务分类">
              <sd-tree-picker
                v-model="model.busiClass"
                single
                :load-tree-data="loadTreeDataBusi"
                a-select
                @change="busiChange"
              >
              </sd-tree-picker>
            </sd-form-item-td>
            <!-- 业务分类ID -->
            <sd-form-item-td :hidden="true" name="busiClassId" label="业务分类ID" />
            <!-- 业务分类name -->
            <sd-form-item-td :hidden="true" name="busiClassName" label="业务分类名称" />
            <!-- 数据来源 -->
            <sd-form-item-td name="dataFrom" label="数据来源" component="a-radio-group">
            </sd-form-item-td>
          </tr>
          <tr v-show="model.dataFrom === 'system'">
            <!-- 数据源 -->
            <td class="ant-form-item-label">
              <label
                title="数据源"
                :class="model.dataFrom === 'system' ? 'ant-form-item-required' : 'ant-form-item'"
              >
                数据源
              </label></td
            >
            <sd-form-item-td name="databaseName" :label="null" :colspan="3">
              <a-form-model-item
                :rules="[
                  {
                    required: model.dataFrom === 'system' ? true : false,
                    trigger: ['change', 'blur'],
                  },
                ]"
                prop="databaseName"
              >
                <a-input
                  v-model="model.databaseName"
                  :read-only="true"
                  @click="selectDatabase"
                ></a-input>
              </a-form-model-item>
              <a-button :loading="connect" :disabled="database === undefined" @click="testDatabase"
                >测试数据源</a-button
              >
            </sd-form-item-td>
          </tr>
          <tr v-show="false">
            <sd-form-item-td name="databaseId" label="数据源ID" :colspan="3"> </sd-form-item-td
          ></tr>
          <tr v-show="model.dataFrom === 'system'">
            <!-- SQL -->
            <td class="ant-form-item-label">
              <label
                title="SQL"
                :class="model.dataFrom === 'system' ? 'ant-form-item-required' : 'ant-form-item'"
              >
                SQL
              </label></td
            >
            <sd-form-item-td name="indiCalSql" :label="null" :colspan="3">
              <a-form-model-item
                :rules="[
                  {
                    required: model.dataFrom === 'system' ? true : false,
                    trigger: ['change', 'blur'],
                  },
                ]"
                prop="indiCalSql"
              >
                <a-textarea v-model="model.indiCalSql" :rows="2" />
              </a-form-model-item>
              <a-button :loading="SQLconnect" @click="checkSQL">校验SQL</a-button>
            </sd-form-item-td>
          </tr>
          <tr v-show="false">
            <!-- 因子指标 -->
            <sd-form-item-td name="indiFactors" label="因子指标" :colspan="3"> </sd-form-item-td>
          </tr>
          <tr v-show="model.dataFrom === 'calculate'">
            <!-- 计算公式描述 -->
            <td class="ant-form-item-label">
              <label
                title="计算公式"
                :class="model.dataFrom === 'calculate' ? 'ant-form-item-required' : 'ant-form-item'"
              >
                计算公式
              </label></td
            >
            <sd-form-item-td name="indiCalFormulaDesc" :label="null" :colspan="3">
              <template v-slot:read-and-edit="editable">
                <kpi-formula-editor
                  ref="formulaindi"
                  :read-only="mode === 'VIEW'"
                  :default-list="
                    model.indiFactors !== undefined ? JSON.parse(model.indiFactors) : []
                  "
                  :data-list="dataList"
                  :zbid="zbid"
                  @change="changeFormula"
                />
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 说明 -->
            <sd-form-item-td name="indiDesc" label="说明" :colspan="3">
              <a-textarea v-model="model.indiDesc" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 是否自动下发报送任务 -->
            <sd-form-item-td name="autoTask" label="是否自动下发报送任务"> </sd-form-item-td>
            <!-- 维护人员 -->
            <sd-form-item-td name="creatorAccount" label="创建人账号" :hidden="true">
            </sd-form-item-td>
            <sd-form-item-td name="creatorName" label="维护人员"> </sd-form-item-td>
          </tr>
          <tr>
            <!-- 维护单位 -->
            <sd-form-item-td name="createDeptId" label="创建部门id" :hidden="true">
            </sd-form-item-td>
            <sd-form-item-td name="createDeptName" label="维护单位"> </sd-form-item-td>
            <!-- 维护日期 -->
            <sd-form-item-td name="creationTime" label="维护日期"> </sd-form-item-td>
          </tr>
          <tr>
            <!-- 监测范围 -->
            <sd-form-item-td name="monitorRange" label="监测范围" component="a-radio-group">
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 阈值说明 -->
            <sd-form-item-td name="thresholdDesc" label="阈值说明" :colspan="3">
              <a-textarea v-model="model.thresholdDesc" :rows="3" />
            </sd-form-item-td>
          </tr>
        </table>

        <table>
          <tr
            ><td :colspan="4">
              <sd-form-item name="kpiIndiOrgEntities" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="expandC"
                    :expand-str="'expandC'"
                    :group-label="'监测单位列表'"
                    @changedClick="changedClick"
                    ><template>
                      <template>
                        <div :class="$style.wrapper">
                          <div v-show="editable" :class="$style.btnselect">
                            <a-button type="link" :class="$style.batchselect" @click="selectDept">
                              <a-icon type="plus-circle" :theme="'filled'" />
                              添加监测单位
                            </a-button>
                            <a-button
                              type="link"
                              :class="$style.batchselect"
                              :disabled="selectedRowKeys.length === 0"
                              @click="syncIndiVal"
                            >
                              <a-icon type="sd-sync" :theme="'filled'" />
                              同步指标设定值
                            </a-button>
                            <a-button
                              type="link"
                              :class="$style.batchselect"
                              :disabled="selectedRowKeys.length === 0"
                              @click="selectSubmiter"
                            >
                              <a-icon type="sd-user" :theme="'filled'" />
                              设置报送人
                            </a-button>
                          </div>
                        </div>
                      </template>

                      <xm-child-table
                        ref="monitorForm"
                        v-model="model.kpiIndiOrgEntities"
                        :read-only="!editable"
                        label=""
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                              attr: {},
                            },
                          ].concat(Array.from(fields.kpiIndiOrgEntities.attr.dync))
                        "
                        :columns="childColumns"
                        :width="1200"
                        :addbuttonvisiable="false"
                        @onSelectChange="onSelectChange"
                      >
                        <!-- 阈值-红 -->
                        <template v-slot:redThresholdDesc="{ field, text, record, index }">
                          <a-input
                            v-if="mode !== 'VIEW'"
                            v-model="record.redThresholdDesc"
                            :read-only="true"
                            @click="configThreshold(index, field)"
                          />
                          <div v-else>{{ record.redThresholdDesc }}</div>
                        </template>
                        <!-- 阈值-黄 -->
                        <template v-slot:yellowThresholdDesc="{ field, text, record, index }">
                          <a-input
                            v-if="mode !== 'VIEW'"
                            v-model="record.yellowThresholdDesc"
                            :read-only="true"
                            @click="configThreshold(index, field)"
                          />
                          <div v-else>{{ record.yellowThresholdDesc }}</div>
                        </template>
                        <!-- 阈值-绿 -->
                        <template v-slot:greenThresholdDesc="{ field, text, record, index }">
                          <a-input
                            v-if="mode !== 'VIEW'"
                            v-model="record.greenThresholdDesc"
                            :read-only="true"
                            @click="configThreshold(index, field)"
                          />
                          <div v-else>{{ record.greenThresholdDesc }}</div>
                        </template>
                        <!-- 监测单位 -->
                        <template v-slot:monitorDeptName="{ field, text, record }">
                          <a-input
                            v-if="mode !== 'VIEW'"
                            v-model="record.monitorDeptName"
                            :read-only="true"
                          />
                          <div v-else>{{ record.monitorDeptName }}</div>
                        </template>
                        <!-- 报送人 -->
                        <template v-slot:submitters="{ field, text, record, index }">
                          <sd-form-item
                            v-if="mode !== 'VIEW'"
                            :name="field.name"
                            :label="null"
                            :input-props="{
                              defaultValue:
                                record.submitters !== undefined &&
                                typeof record.submitters !== 'object'
                                  ? JSON.parse(record.submitters)
                                  : record.submitters,
                            }"
                            @change="changeSubmitters($event, index)"
                          />
                          <div v-else>{{ record.submitterName }}</div>
                        </template>
                        <!-- 报送部门 -->
                        <template v-slot:submitterDeptName="{ field, text, record }">
                          <a-input
                            v-if="mode !== 'VIEW'"
                            v-model="record.submitterDeptName"
                            :read-only="true"
                          />
                          <div v-else>{{ record.submitterDeptName }}</div>
                        </template>
                      </xm-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item></td
            >
          </tr>
        </table>

        <!-- 选择数据源 -->
        <iam-audit-modal
          :single="true"
          :check-type="'radio'"
          select-type="table"
          :visible="databaseVisible"
          :columns="databaseColumns"
          :treeparams="{
            configId: '61',
          }"
          @listSelected="listSelected"
          @getCheckNode="getCheckNode"
          @handleCancel="handleselectsjyCancel"
        ></iam-audit-modal>
        <!-- 阈值配置器 -->
        <a-modal
          ref="thresholdModal"
          title="阈值配置器"
          :destroy-on-close="true"
          :visible="thresholdVisible"
          width="1200px"
          @ok="handleOk"
          @cancel="handleCancel"
        >
          <kpi-threshold-config ref="thresholdConfig" :value="editFormVal"></kpi-threshold-config>
        </a-modal>
      </template>
    </sd-detail-form>
  </audit-form-top-banner>
</template>

<script>
import axios from '@/common/services/axios-instance'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import { message } from '@/common/one-ui'
import pickValues from '@/common/services/pick-values'
import sdTreePicker from '@/common/components/sd-tree-picker.vue'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import auditFormTopBanner from '@product/iam/components/audit-form-top-banner'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import iamAuditModal from '@product/iam/components/iam-audit-modal.vue'
import kpiFormulaEditor from '../components/kpi-formula-editor'
import kpiThresholdConfig from '../components/kpi-threshold-config.vue'
import KpiService from '../kpi-service'
import components from './_import-components/kpi-indi-form-import'
import 'element-ui/lib/theme-chalk/index.css'

export default {
  name: 'KpiIndiForm',
  metaInfo: {
    title: '指标定义表单',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    auditFormTopBanner,
    kpiFormulaEditor,
    kpiThresholdConfig,
    iamAuditModal,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      databaseVisible: false, // 数据源选择
      thresholdVisible: false, // 阈值配置器
      connect: false, // 测试数据源连接按钮状态
      SQLconnect: false, // 校验SQL连接按钮状态
      expandC: true,
      mode: null,
      saveFlag: true,
      basicExpand: true,
      childColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '60px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'indiId', sdHidden: true },
        { dataIndex: 'monitorDeptId', sdHidden: true },
        { dataIndex: 'monitorDeptCode', sdHidden: true },
        { dataIndex: 'monitorDeptName', title: '监测单位' },
        { dataIndex: 'submitterId', sdHidden: true },
        { dataIndex: 'submitterAccount', sdHidden: true },
        { dataIndex: 'submitterName', title: '报送人姓名', sdHidden: true },
        { dataIndex: 'submitters', title: '报送人' },
        { dataIndex: 'submitterDeptId', sdHidden: true },
        { dataIndex: 'submitterDeptCode', sdHidden: true },
        { dataIndex: 'submitterDeptName', title: '报送部门' },
        { dataIndex: 'redThreshold', sdHidden: true },
        { dataIndex: 'redThresholdValue', sdHidden: true },
        { dataIndex: 'redThresholdDesc', title: '指标阈值(红)' },
        { dataIndex: 'yellowThreshold', sdHidden: true },
        { dataIndex: 'yellowThresholdValue', sdHidden: true },
        { dataIndex: 'yellowThresholdDesc', title: '指标阈值(黄)' },
        { dataIndex: 'greenThreshold', sdHidden: true },
        { dataIndex: 'greenThresholdValue', sdHidden: true },
        { dataIndex: 'greenThresholdDesc', title: '指标阈值(绿)' },
        { dataIndex: 'izSelf', title: '是否本单位', sdHidden: true },
      ],
      dataList: [],
      databaseColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '数据源名称',
          dataIndex: 'name',
        },
        {
          title: '数据库类型',
          dataIndex: 'databaseType',
        },
        {
          title: 'IP地址',
          dataIndex: 'host',
        },
        {
          title: '端口号',
          dataIndex: 'port',
        },
        {
          title: '数据库名称',
          dataIndex: 'useSchema',
        },
        {
          title: '用户名',
          dataIndex: 'userName',
          sdHidden: true,
        },
        {
          title: 'password',
          dataIndex: 'password',
          sdHidden: true,
        },
      ],
      busicateColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
      ],
      defaultExpandedKeys: [], // 默认展开部门节点
      rootNode: undefined, // 根节点
      hierarchical: undefined, // 分级授权
      selectedRowKeys: [], // 选择的子表行
      treeparams: {
        // 业务分类树
        configId: 101,
      },
      zbid: this.$route.query.record ? this.$route.query.record : '',
      editFormVal: '',
      database: undefined,
    }
  },
  methods: {
    handleselectsjyCancel() {
      this.databaseVisible = false
    },
    changeFormula(value) {
      let Formulav = ''
      let FormulavDesc = ''
      value.forEach((v, index) => {
        if (v.type === 'obj') {
          Formulav += v.key
          FormulavDesc += v.value
        } else {
          Formulav += v.value
          FormulavDesc += v.value
        }
      })
      this.$refs.kpiIndiForm.setFieldValue('indiCalFormulaDesc', FormulavDesc)
      this.$refs.kpiIndiForm.setFieldValue('indiCalFormula', Formulav)
      this.$refs.kpiIndiForm.setFieldValue('indiFactors', JSON.stringify(value))
    },
    // 页面加载完成后
    sdFormReady() {
      this.mode = this.$refs.kpiIndiForm.formData.mode
      if (this.$route.query.mode === 'view') {
        this.mode = 'VIEW'
      }
    },
    // 保存
    saveForm() {
      // 保存子表数据
      this.$refs.kpiIndiForm.setFieldValue('kpiIndiOrgEntities', this.$refs.monitorForm.value)
      // 校验计算公式需要选择指标 dataFrom === 'calculate'
      const zsfs = this.$refs.kpiIndiForm.getFieldValue('dataFrom')
      let flag = true
      if (zsfs === 'calculate') {
        const gsdesc = this.$refs.kpiIndiForm.getFieldValue('indiCalFormulaDesc')
        const gs = this.$refs.kpiIndiForm.getFieldValue('indiCalFormula')
        if (gs.indexOf('#') === -1) {
          flag = false
        }
      }

      var jobFrequency = this.$refs.kpiIndiForm.getFieldValue('jobFrequency')
      var jobCron = this.$refs.kpiIndiForm.getFieldValue('jobCron')
      var id = this.$refs.kpiIndiForm.getFieldValue('id')
      const params = {
        id: id,
        jobFrequency: jobFrequency,
        jobCron: jobCron,
      }
      KpiService.hasJobFrequency(params).then((res) => {
        if (res) {
          message.error('该时间维度已存在，请重新选择！')
        } else {
          this.$refs.kpiIndiForm.validateFields().then(() => {
            if (!flag) {
              message.error('计算公式中必须选择至少一项指标！')
            } else {
              message.success('保存成功').then(() => {
                this.$refs.kpiIndiForm.saveBtnClick()
              })
            }
          })
        }
      })
    },
    saved() {
      this.close(true)
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    handleIndiNo(rule, value, callback) {
      const id = this.$refs.kpiIndiForm.getFieldValue('id')
      // 编号重复校验
      KpiService.hasIndiNo(id, value)
        .then((res) => {
          if (res) {
            callback(new Error('编号重复，请重新输入'))
          } else {
            callback()
          }
        })
        .catch((err) => {
          // eslint-disable-next-line no-console
          console.log(err)
          message.error('出错了，请联系管理员', 1)
          callback(new Error('编号校验出错，请联系管理员'))
        })
    },
    listSelected(keys, keyinfos) {
      // 数据源数据赋值
      this.databaseVisible = false
      if (keyinfos?.length > 0) {
        this.database = keyinfos[0]
        this.$refs.kpiIndiForm.setFieldValue('databaseName', keyinfos[0].name)
        this.$refs.kpiIndiForm.setFieldValue('databaseId', parseInt(keyinfos[0].id))
      }
    },
    getCheckNode(checkNode) {
      // 数据源弹窗选择
      this.databaseVisible = false
    },
    selectDatabase() {
      // 选择数据源
      this.databaseVisible = true
    },
    testDatabase() {
      this.connect = true
      // 测试数据源
      const databaseBean = {
        databaseType: this.database?.databaseType,
        host: this.database?.host,
        port: this.database?.port,
        useSchema: this.database?.useSchema,
        userName: this.database?.userName,
        password: this.database?.password,
      }
      axios({
        url: 'api/xcoa-mobile/v1/iamfinsysdatabase/testDbConnection',
        method: 'post',
        data: databaseBean,
      })
        .then((res) => {
          if (res.data.indexOf('成功') !== -1) {
            message.success(res.data, 1)
          } else {
            message.error(res.data, 1)
          }
          setTimeout(() => {
            this.connect = false
          }, 2000)
        })
        .catch((err) => {
          // eslint-disable-next-line no-console
          console.log(err)
          message.error('出错了，请联系管理员', 1)
          setTimeout(() => {
            this.connect = false
          }, 2000)
        })
    },
    checkSQL() {
      // 校验SQL
      this.SQLconnect = true
      const databaseID = this.$refs.kpiIndiForm.getFieldValue('databaseId') // 数据源ID
      const sql = this.$refs.kpiIndiForm.getFieldValue('indiCalSql') // SQL
      const param = {
        id: databaseID,
        sql: sql,
      }
      KpiService.validateSQL(param)
        .then((res) => {
          if (res.indexOf('成功') !== -1) {
            message.success(res, 1)
          } else {
            message.error(res, 1)
          }
          setTimeout(() => {
            this.SQLconnect = false
          }, 2000)
        })
        .catch((err) => {
          // eslint-disable-next-line no-console
          console.log(err)
          message.error('出错了，请联系管理员', 1)
          setTimeout(() => {
            this.SQLconnect = false
          }, 2000)
        })
    },
    // 获取用于选择的业务类型分类树
    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
      })
    },
    busicateHandleCancel() {
      this.busicateVisible = false
    },
    configThreshold(index, field) {
      // 阈值配置器
      this.editIndex = index // 编辑行index
      this.editFieldDesc = field.name // 编辑阈值
      // 阈值公式字段
      switch (field.name) {
        case 'redThresholdDesc':
          // 红
          this.editField = 'redThreshold'
          break
        case 'yellowThresholdDesc':
          // 黄
          this.editField = 'yellowThreshold'
          break
        case 'greenThresholdDesc':
          // 绿
          this.editField = 'greenThreshold'
          break
        default:
          break
      }
      const fieldForm = this.editField + 'Value'
      this.editFormVal = this.$refs.monitorForm.value[this.editIndex][fieldForm]
      // 阈值配置器
      this.thresholdVisible = true
    },
    handleOk() {
      // 阈值赋值
      const configVal = this.$refs.thresholdConfig.getConfigVal() // 阈值配置器返回值
      const fieldForm = this.editField + 'Value'
      this.$refs.monitorForm.value[this.editIndex][fieldForm] = configVal.dynamicItem // 阈值表单数据
      this.$refs.monitorForm.value[this.editIndex][this.editFieldDesc] = configVal.strconfig // 阈值描述-显示用
      this.$refs.monitorForm.value[this.editIndex][this.editField] = configVal.calconfig.replace(
        /DEPTCODE/g,
        this.$refs.monitorForm.value[this.editIndex].monitorDeptCode
      ) // 阈值公式
      this.thresholdVisible = false
    },
    handleCancel() {
      this.thresholdVisible = false
    },
    onSelectChange(keys) {
      // 所选子表行
      this.selectedRowKeys = keys
    },
    selectSubmiter() {
      // 设置报送人
      pickValues(
        sdUserPicker, // 第一个参数：使用的选择器组件
        // 第二个参数：传递给选择器的props。默认选中的值、是否单选等，都可以传递
        {
          single: true, // 单选
        }
      )
        // 用户选择完成后，promise返回选中的值。用户取消返回undefined
        .then((values) => {
          // 子表行报送人员赋值 code name
          if (values && values[0]) {
            // 获取报送人部门信息
            KpiService.getSubmitterInfo('', values[0].code)
              .then((res) => {
                if (res) {
                  // 子表赋值
                  this.selectedRowKeys?.forEach((item) => {
                    this.$refs.monitorForm.value[item].submitters = JSON.stringify(values) // 报送人
                    this.$refs.monitorForm.value[item].submitterId = res.submitterId // 报送人id
                    this.$refs.monitorForm.value[item].submitterAccount = res.submitterAccount // 报送人account
                    this.$refs.monitorForm.value[item].submitterName = res.submitterName // 报送人名称
                    this.$refs.monitorForm.value[item].submitterDeptId = res.submitterDeptId // 报送人部门id
                    this.$refs.monitorForm.value[item].submitterDeptCode = res.submitterDeptCode // 报送人部门code
                    this.$refs.monitorForm.value[item].submitterDeptName = res.submitterDeptName // 报送人部门名称
                  })

                  // 更新子表数据
                  this.$refs.kpiIndiForm.setFieldValue(
                    'kpiIndiOrgEntities',
                    this.$refs.monitorForm.value
                  )
                  // 刷新子表值
                  this.$refs.monitorForm.fnupdate(this.$refs.monitorForm.value)
                }
              })
              .catch((err) => {
                // eslint-disable-next-line no-console
                console.log(err)
                message.error('出错了，请联系管理员')
              })
          }
        })
        .catch((err) => {
          // eslint-disable-next-line no-console
          console.log(err)
          message.error('出错了，请联系管理员')
        })
    },
    syncIndiVal() {
      // 同步指标设定值
      const datasource = []
      const mform = this.$refs.monitorForm.value // 子表值
      // 生成阈值选择器数据源--《监测单位列表》中‘指标阈值（红）、指标阈值（黄）、指标阈值（绿）’都不为空的‘监测单位’
      mform?.forEach((item) => {
        // 筛选‘指标阈值（红）、指标阈值（黄）、指标阈值（绿）’都不为空的‘监测单位’
        if (item.redThreshold && item.yellowThreshold && item.greenThreshold) {
          datasource.push({
            id: item.monitorDeptId, // 监测部门ID
            name: item.monitorDeptName, // 监测部门
            monitorDeptCode: item.monitorDeptCode,
            redThreshold: item.redThreshold,
            redThresholdDesc: item.redThresholdDesc,
            yellowThreshold: item.yellowThreshold,
            yellowThresholdDesc: item.yellowThresholdDesc,
            greenThreshold: item.greenThreshold,
            greenThresholdDesc: item.greenThresholdDesc,
            excellentVal: item.excellentVal,
            fineVal: item.fineVal,
            avgVal: item.avgVal,
            lowVal: item.lowVal,
            badVal: item.badVal,
          })
        }
      })
      // 选择弹框
      pickValues(
        sdTreePicker, // 第一个参数：使用的选择器组件
        // 第二个参数：传递给选择器的props。默认选中的值、是否单选等，都可以传递
        {
          loadTreeData: () => {
            return datasource
          },
          single: true,
        }
      )
        // 用户选择完成后，promise返回选中的值。用户取消返回undefined
        .then((values) => {
          // 赋值所选子表行指标阈值及参考值的配置内容
          if (values && values[0]) {
            // 子表赋值
            this.selectedRowKeys?.forEach((item) => {
              this.$refs.monitorForm.value[item].redThreshold = values[0].redThreshold
              this.$refs.monitorForm.value[item].redThresholdDesc = values[0].redThresholdDesc
              this.$refs.monitorForm.value[item].yellowThreshold = values[0].yellowThreshold
              this.$refs.monitorForm.value[item].yellowThresholdDesc = values[0].yellowThresholdDesc
              this.$refs.monitorForm.value[item].greenThreshold = values[0].greenThreshold
              this.$refs.monitorForm.value[item].greenThresholdDesc = values[0].greenThresholdDesc
              this.$refs.monitorForm.value[item].excellentVal = values[0].excellentVal
              this.$refs.monitorForm.value[item].fineVal = values[0].fineVal
              this.$refs.monitorForm.value[item].avgVal = values[0].avgVal
              this.$refs.monitorForm.value[item].lowVal = values[0].lowVal
              this.$refs.monitorForm.value[item].badVal = values[0].badVal
            })
            // 刷新子表值
            this.$refs.monitorForm.fnupdate(this.$refs.monitorForm.value)
          }
        })
        .catch((err) => {
          // eslint-disable-next-line no-console
          console.log(err)
          message.error('出错了，请联系管理员')
        })
    },
    selectDept() {
      // 选择监测单位
      pickValues(
        sdTreePicker, // 第一个参数：使用的选择器组件
        // 第二个参数：传递给选择器的props。默认选中的值、是否单选等，都可以传递
        {
          loadTreeData: (id) => {
            return this.loadTreeData(id)
          },
        }
      )
        // 用户选择完成后，promise返回选中的值。用户取消返回undefined
        .then((values) => {
          // 新增子表行
          if (values && values[0]) {
            // 监测单位唯一性判断
            const monitor = this.$refs.monitorForm.value
            const flag = values.filter((vitem) => {
              return monitor?.find((ditem) => {
                return vitem.code === ditem.monitorDeptCode
              })
            })
            if (flag && flag[0]) {
              message.warning('监测单位重复，请重新选择。')
              return false
            }
            // 判断是否本单位
            const deptId = this.$refs.kpiIndiForm.getFieldValue('createDeptId') // 创建部门ID
            const monitorDeptIds = [] // 监测单位IDS
            values?.forEach((item) => {
              monitorDeptIds.push(item.id)
            })
            KpiService.sameCompany(deptId, monitorDeptIds)
              .then((res) => {
                // 增加子表行
                values?.forEach((item) => {
                  this.$refs.monitorForm.value.push({
                    monitorDeptId: item.id, // 监测单位ID
                    monitorDeptCode: item.code, // 监测单位code
                    monitorDeptName: item.name, // 监测单位name
                    izSelf: res[item.id] + '', // 是否本单位
                    submitters: '[]',
                    submitterId: '',
                    submitterAccount: '',
                    submitterName: '',
                    submitterDeptId: '',
                    submitterDeptCode: '',
                    submitterDeptName: '',
                    redThreshold: '',
                    redThresholdValue: '',
                    redThresholdDesc: '',
                    yellowThreshold: '',
                    yellowThresholdValue: '',
                    yellowThresholdDesc: '',
                    greenThreshold: '',
                    greenThresholdValue: '',
                    greenThresholdDesc: '',
                  })
                })
              })
              .catch((err) => {
                // eslint-disable-next-line no-console
                console.log(err)
                message.error('出错了，请联系管理员')
              })
          }
        })
        .catch((err) => {
          // eslint-disable-next-line no-console
          console.log(err)
          message.error('出错了，请联系管理员')
        })
    },
    loadTreeData(id) {
      // 监测单位组织机构
      if (!id) {
        const expandedKey = this.defaultExpandedKeys
        if (Array.isArray(this.rootNode)) {
          return Promise.all(
            this.rootNode.map((rootNode) => {
              return KpiService.getGroupTree({
                expandedKey,
                rootNode,
                hierarchical: this.hierarchical,
                levPath: true,
              })
            })
          ).then((nodes) => {
            return nodes.map((node) => node[0])
          })
        } else {
          return KpiService.getGroupTree({
            expandedKey,
            rootNode: this.rootNode,
            hierarchical: this.hierarchical,
            levPath: true,
          })
        }
      } else {
        return KpiService.getChildNodes(id, {
          type: 'G',
          isContainSub: false,
          hierarchical: this.hierarchical,
          levPath: true,
        }).then((res) => {
          return res.map((item) => {
            item.checkable = true
            return item
          })
        })
      }
    },
    busiChange(val) {
      // 业务分类id,name赋值
      if (val && val[0]) {
        this.$refs.kpiIndiForm.setFieldValue('busiClassId', val[0].id)
        this.$refs.kpiIndiForm.setFieldValue('busiClassName', val[0].name)
      }
    },
    changeSubmitters(val, index) {
      // 报送人信息赋值
      if (val && val[0]) {
        // 获取报送人部门信息
        KpiService.getSubmitterInfo('', val[0].code)
          .then((res) => {
            if (res) {
              // 子表赋值
              this.$refs.monitorForm.value[index].submitters = JSON.stringify(val)
              this.$refs.monitorForm.value[index].submitterId = res.submitterId // 报送人id
              this.$refs.monitorForm.value[index].submitterAccount = res.submitterAccount // 报送人account
              this.$refs.monitorForm.value[index].submitterName = res.submitterName // 报送人名称
              this.$refs.monitorForm.value[index].submitterDeptId = res.submitterDeptId // 报送人部门id
              this.$refs.monitorForm.value[index].submitterDeptCode = res.submitterDeptCode // 报送人部门code
              this.$refs.monitorForm.value[index].submitterDeptName = res.submitterDeptName // 报送人部门名称

              // 更新子表数据
              this.$refs.kpiIndiForm.setFieldValue(
                'kpiIndiOrgEntities',
                this.$refs.monitorForm.value
              )
            }
          })
          .catch((err) => {
            // eslint-disable-next-line no-console
            console.log(err)
            message.error('出错了，请联系管理员')
          })
      } else {
        // 清空报送人信息
        this.$refs.monitorForm.value[index].submitters = '[]'
        this.$refs.monitorForm.value[index].submitterId = '' // 报送人id
        this.$refs.monitorForm.value[index].submitterAccount = '' // 报送人account
        this.$refs.monitorForm.value[index].submitterName = '' // 报送人名称
        this.$refs.monitorForm.value[index].submitterDeptId = '' // 报送人部门id
        this.$refs.monitorForm.value[index].submitterDeptCode = '' // 报送人部门code
        this.$refs.monitorForm.value[index].submitterDeptName = '' // 报送人部门名称
        // 更新子表数据
        this.$refs.kpiIndiForm.setFieldValue('kpiIndiOrgEntities', this.$refs.monitorForm.value)
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';
.form {
  :global(td.ant-form-item-label > label) {
    white-space: normal !important;
  }
  .connect-btn {
    float: right;
    font-weight: 400;
    font-size: 16px;
    top: 8px;
    cursor: pointer;
    margin-right: 10px;
  }
  .first-td {
    border: none !important;
    padding: 0;
  }
  .btnselect {
    position: relative;
    top: 4px;
    right: 100px;
    float: right;
    .batchselect {
      z-index: 100;
      margin-left: 10px;
    }
  }
}
.read-only-form {
  :global(.ant-form-item-required):before {
    display: none;
  }
}
</style>
