<template>
  <div>
    <sd-webflow
      ref="flow"
      :removed-tabs="['sdRelatedDoc']"
      :class="$style.form"
      :validate-form="validForm"
    >
      <template v-slot:form="{ 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="title" label="预警内容" :colspan="3" />
          </tr>
          <tr>
            <!-- 接收人 -->
            <sd-form-item-td name="receiverMember" @change="userChange" />
            <!-- 接收人id -->
            <sd-form-item-td name="receiverId" :hidden="true" />
            <!-- 接收人account -->
            <sd-form-item-td name="receiverAccount" :hidden="true" />
            <!-- 接收人中文名 -->
            <sd-form-item-td name="receiverName" :hidden="true" />
            <!-- 联系电话 -->
            <sd-form-item-td name="contactPhone"> </sd-form-item-td>
          </tr>
          <tr>
            <!-- 接收单位 -->
            <sd-form-item-td name="receiverDeptMember" label="接收单位">
              <template v-slot:read-and-edit="{ editable }">
                {{ getDeptName(model.receiverDeptMember) }}
              </template>
            </sd-form-item-td>
            <!-- 办理时限 -->
            <sd-form-item-td name="limitDate" />
          </tr>
          <tr>
            <!-- 说明 -->
            <sd-form-item-td name="remark" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <a-textarea
                  v-if="editable"
                  v-model="model.remark"
                  :auto-size="{ minRows: 3, maxRows: 3 }"
                ></a-textarea>
                <div v-else>
                  {{ model.remark }}
                </div>
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 附件 -->
            <sd-form-item-td name="attachment" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <sd-attachment
                  v-model="model.attachment"
                  :group-id="JSON.parse(fields.attachment.value).value"
                  :read-only="!editable"
                ></sd-attachment>
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 创建人员 -->
            <sd-form-item-td name="creatorName" />
            <!-- 创建单位 -->
            <sd-form-item-td name="createDeptName" />
          </tr>
          <tr>
            <!-- 创建日期 -->
            <sd-form-item-td v-show="formReady()" name="creationTime" :colspan="3" />
          </tr>
        </table>

        <table>
          <tr :class="$style.childTableTr">
            <!-- 预警指标 -->
            <sd-form-item-td name="kpiAlertOrderDetailList" :label="null" :colspan="4">
              <template v-slot:read-and-edit="{ editable }">
                <audit-advanced-group
                  :expand="orderExpand"
                  expand-str="orderExpand"
                  group-label="预警指标"
                  @changedClick="changedClick"
                >
                  <template>
                    <div v-show="showBtn && orderExpand && editable" :class="$style.btnselect">
                      <a-button type="link" :class="$style.batchselect" @click="showSelectName">
                        <a-icon type="check-circle" :theme="'filled'" />
                        选择
                      </a-button>
                    </div>
                    <kpi-alert-order-child-table
                      :key="childTableKey"
                      ref="orderTable"
                      v-model="model.kpiAlertOrderDetailList"
                      :class="$style.orderChild"
                      :edit-row="editRow"
                      :show-btn="showBtn"
                      :label="null"
                      :read-only="false"
                      :addbuttonvisiable="false"
                      :fields="
                        [
                          {
                            caption: '序号',
                            name: 'sortNum',
                            dataType: 'number',
                          },
                        ]
                          .concat(Array.from(fields.kpiAlertOrderDetailList.attr.dync))
                          .concat([
                            {
                              caption: '操作',
                              name: 'action',
                              dataType: 'string',
                            },
                          ])
                      "
                      :columns="orderColumns"
                    >
                      <!-- 指标名称 -->
                      <template v-slot:indiName="{ field, text, record }">
                        <a :title="text" @click="rowClick($event, record)">{{ text }}</a>
                      </template>
                      <!-- 数据时期 -->
                      <template v-slot:dataPeriod="{ field, text, record }">
                        {{ record.year + '年' + record.dataPeriod }}
                      </template>
                      <!-- 指标值单位 -->
                      <template v-slot:indiUnit="{ field, text }">
                        {{ text }}
                      </template>
                      <!-- 预警状态 -->
                      <template v-slot:alertStatus="{ field, text, record }">
                        <div
                          :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
                          >
                        </div>
                      </template>
                      <!-- 操作 -->
                      <template v-slot:action="{ field, text, record }">
                        <a :title="text">反馈</a>
                      </template>

                      <!-- 表单插槽 -->
                      <template v-slot:form="{ fields, model }">
                        <!-- 异常原因 -->
                        <sd-form-item name="abnormalReason" :label="'异常原因'">
                          <template v-slot:read-and-edit="{ editable }">
                            <a-textarea
                              v-model="model.abnormalReason"
                              :auto-size="{ maxRows: 3, minRows: 3 }"
                            ></a-textarea>
                          </template>
                        </sd-form-item>
                        <!-- 整改措施 -->
                        <sd-form-item name="correctWay" :label="'整改措施'">
                          <template v-slot:read-and-edit="{ editable }">
                            <a-textarea
                              v-model="model.correctWay"
                              :auto-size="{ maxRows: 3, minRows: 3 }"
                            ></a-textarea>
                          </template>
                        </sd-form-item>
                        <!-- 附件 -->
                        <sd-form-item name="attachment" :label="'附件'"> </sd-form-item>
                      </template>
                    </kpi-alert-order-child-table>
                  </template>
                </audit-advanced-group>
              </template>
            </sd-form-item-td>
          </tr>
        </table>
      </template>
    </sd-webflow>
    <!-- 异常指标选择器 -->
    <kpi-analysis-select-modal
      :visible="visible"
      type="yc"
      :select-expressions="[
        {
          dataType: 'long',
          name: 'creationTime',
          op: 'ge',
          longValue: `${new Date(new Date().getFullYear() - 1 + '-01-01 00:00:00').getTime()}`,
        },
      ]"
      @handleCancel="handleCancel"
      @handleOk="handleOk"
    />
  </div>
</template>

<script>
import { message } from '@/common/one-ui'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
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 kpiAlertOrderChildTable from './kpi-alert-order-child-table.vue'
import kpiAlertOrderService from './kpi-alert-order-service'
import components from './_import-components/kpi-alert-order-form-import'

export default {
  name: 'KpiAlertOrderForm',
  metaInfo: {
    title: '指标预警单',
  },
  components: {
    kpiAlertOrderChildTable,
    kpiAnalysisSelectModal,
    auditAdvancedGroup,
    ...components,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      isReady: false,
      childTableKey: 0,
      indiUnitDict: [], // 指标值单位字典
      editRow: false,
      showBtn: false,
      visible: false,
      expand: true,
      orderExpand: true,
      orderColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'indiId', sdHidden: true },
        { dataIndex: 'monitorId', sdHidden: true },
        { dataIndex: 'orderId', sdHidden: true },
        { dataIndex: 'monitorDeptId', sdHidden: true },
        { dataIndex: 'monitorDeptCode', sdHidden: true },
        { dataIndex: 'year', sdHidden: true },
        {
          title: '指标名称',
          dataIndex: 'indiName',
        },
        {
          title: '指标编号',
          dataIndex: 'indiNo',
        },
        {
          title: '指标时间维度',
          dataIndex: 'indiFrequency',
        },
        {
          title: '监测单位',
          dataIndex: 'monitorDeptName',
        },
        {
          title: '数据时期',
          dataIndex: 'dataPeriod',
        },
        { title: '指标值', dataIndex: 'indiVal' },
        { title: '指标值单位', dataIndex: 'indiUnit' },
        { title: '预警状态', dataIndex: 'alertStatus' },
        { title: '异常原因', dataIndex: 'abnormalReason' },
        { title: '整改措施', dataIndex: 'correctWay' },
        { title: '附件', dataIndex: 'attachment', width: '230px' },
      ],
    }
  },
  created() {
    // 获取指标值单位
    kpiAlertOrderService.getDictValue('INDI_UNIT').then((res) => {
      this.indiUnitDict = res.data
    })
    if (this.$route.query.extParams) {
      const e = this.$route.query.extParams
      const eo = JSON.parse(e)
      const id = eo.zbid
      KpiService.getIndiMonitorsByIds(id).then((res) => {
        if (res.data) {
          let data = []
          res.data.forEach((item) => {
            if (item.monitorDeptNameStrs.indexOf(',') > -1) {
              const monitorDepts = item.monitorDeptNameStrs.split(',')
              const monitorDeptsid = item.monitorDeptIdStrs.split(',')
              const alertStatus = item.alertStatus.split(',')
              const indiUnit = item.indiUnit.split(',')
              const indiVal = item.indiVal.split(',')
              const indiNo = item.indiNo.split(',')
              const year = item.year.split(',')
              const dataPeriod = item.dataPeriod.split(',')
              const monitorId = item.id.split(',')
              monitorDepts.forEach((mitem, mindex) => {
                const nitem = { ...item }
                nitem.monitorDeptStr = mitem
                nitem.monitorDeptId = monitorDeptsid[mindex]
                nitem.alertStatus = alertStatus[mindex]
                nitem.indiUnit = indiUnit[mindex]
                nitem.indiVal = indiVal[mindex]
                nitem.indiNo = indiNo[mindex]
                nitem.year = year[mindex]
                nitem.dataPeriod = dataPeriod[mindex]
                nitem.monitorId = monitorId[mindex]
                data = this.fnpd(data, nitem)
              })
            } else {
              item.monitorDeptId = item.monitorDeptIdStrs
              item.monitorDeptStr = item.monitorDeptNameStrs
              item.monitorId = item.id
              data = this.fnpd(data, item)
            }
          })
          this.$refs.flow.setFieldValue('kpiAlertOrderDetailList', data)
        }
      })
    }
  },
  methods: {
    fnpd(data, d) {
      const attach = this.fncreaterd()
      data.push({
        id: null,
        indiId: d.indiId,
        monitorId: d.monitorId,
        monitorDeptId: d.monitorDeptId,
        monitorDeptCode: d.monitorDeptCode,
        indiName: d.indiName,
        indiNo: d.indiNo,
        indiFrequency: d.indiFrequency,
        monitorDeptName: d.monitorDeptStr,
        dataTime: d.dataTime,
        year: d.year,
        dataPeriod: d.dataPeriod,
        indiVal: d.indiVal,
        indiUnit: d.indiUnit,
        alertStatus: d.alertStatus,
        attachment: '{"value":"' + attach + '"}',
      })
      return data
    },
    fncreaterd() {
      var num = ''
      for (var i = 0; i < 17; i++) {
        if (i === 0) {
          num += Math.floor(Math.random() * 9 + 1)
        } else {
          num += Math.floor(Math.random() * 10)
        }
      }
      return num
    },
    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 tableData = this.$refs.flow.getFieldValue('kpiAlertOrderDetailList')
      const tableId = tableData.map((item) => item.monitorId + '')
      const selectData = []
      let flag = false // 会否有重复
      rows.forEach((item) => {
        item.monitorDeptName = item.monitorDeptStr
        item.monitorId = item.id
        item.indiNo = item.indiNo.includes(',') ? item.indiNo.split(',')[0] : item.indiNo
        item.id = null
        item.attachment =
          '{"value":"' + Math.round(Math.random() * 100000000000000000).toString() + '"}'
        if (!tableId.includes(item.monitorId)) {
          selectData.push(item)
        } else {
          flag = true
        }
      })
      if (flag) {
        message.info('请勿选择重复数据', 1)
      }
      this.$refs.flow.setFieldValue('kpiAlertOrderDetailList', tableData.concat(selectData))
      this.handleCancel()
    },
    // 异常指标选择取消
    handleCancel(event) {
      this.visible = false
    },
    // 用户变化时
    userChange(val) {
      if (val.length === 0) {
        this.$refs.flow.setFieldValue('receiverDeptMember', [])
        return
      }
      this.$refs.flow.setFieldValue('receiverAccount', val[0].code)
      this.$refs.flow.setFieldValue('receiverName', val[0].name)
      kpiAlertOrderService.getGroupByUserAccount(val[0].code).then((res) => {
        this.$refs.flow.setFieldValue('receiverDeptMember', [
          {
            id: res.data.id,
            text: res.data.name,
            leaf: false,
            expandable: true,
            differentDisplay: false,
            props: {
              expandFlag: 'false',
              code: res.data.code,
              fullpath: '',
              weight: res.data.props.weight,
              fullpathId: '',
              type: 'G',
              lev: res.data.props.lev,
              levPath: res.data.name,
            },
            title: res.data.name,
            code: res.data.id,
            name: res.data.name,
            type: 'Group',
          },
        ])
      })
    },
    // 表单加载时
    formReady() {
      if (this.$refs.flow) {
        if (this.isReady) return true
        this.isReady = true
        this.orderColumns.push({
          title: '操作',
          dataIndex: 'action',
          sdHidden: true,
        })
        if (this.$refs.flow.FlowData.mode === 'VIEW') {
          this.editRow = false
          this.showBtn = false
        } else if (this.$refs.flow.FlowData.attrs.kpi$alertOrderReview) {
          this.editRow = true
          this.orderColumns.find((item) => {
            return item.dataIndex === 'action'
          }).sdHidden = false
          this.childTableKey++
        }
        // 起草环节不能编辑行
        if (this.$refs.flow.FlowData.attrs.stepN === 0) {
          this.editRow = false
          this.showBtn = true
        }
      }
      return true
    },
    // 获取指标值单位
    getIndiUnitValue(val) {
      return this.indiUnitDict.find((item) => {
        return item.id === val
      })?.name
    },
    getDeptName(val) {
      if (val && val.length !== 0) {
        return val[0].name
      } else {
        return ''
      }
    },
    // 自定义校验
    validForm() {
      // 获取环节号
      const flowNum = this.$refs.flow.flowData.attrs.stepN
      // 起草环节才校验，至少选择一条指标定义单，否则无意义
      if (flowNum === 0) {
        const data = this.$refs.flow.getFieldValue('kpiAlertOrderDetailList')
        if (data.length === 0) {
          message.info('请选择需要预警的异常指标', 1)
          return Promise.resolve(false)
        }
        return Promise.resolve(true)
      } else {
        return Promise.resolve(true)
      }
    },
  },
}
</script>

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