<template>
  <div>
    <sd-webflow
      ref="flow"
      :removed-tabs="['sdRelatedDoc']"
      :class="$style.flowform"
      @saveproject="saveproject"
      @actionBtnClick="actionBtnClick"
    >
      <template v-slot:form="{ model, fields }">
        <table>
          <tr>
            <!-- 任务名称 -->
            <sd-form-item-td name="taskName" />
            <!-- 报送人 -->
            <sd-form-item-td name="submitterName" />
          </tr>
          <tr>
            <!-- 报送部门 -->
            <sd-form-item-td name="submitterDeptName" />
            <!-- 创建日期 -->
            <sd-form-item-td name="creationTime" />
          </tr>
          <!-- 任务明细子表 -->
          <tr>
            <sd-form-item-td :label="null" name="indiTaskDetailList" :colspan="4">
              <template v-slot:read-and-edit="{ editable }">
                <template>
                  <div :class="$style.wrapper">
                    <div v-show="editable && sysFlag" :class="$style.btnselect">
                      <a-button
                        type="primary"
                        :loading="loading"
                        :class="$style.batchselect"
                        @click="calGuideVal"
                      >
                        重新计算系统参考值
                      </a-button>
                    </div>
                  </div>
                </template>
                <xm-child-table
                  ref="childForm"
                  v-model="model.indiTaskDetailList"
                  :read-only="!editable"
                  label=""
                  :fields="fields.indiTaskDetailList.attr.dync"
                  :columns="childColumns"
                  :width="1200"
                  :captionvisiable="false"
                  :show-selection="
                    () => {
                      return false
                    }
                  "
                >
                  <!-- 指标编码 -->
                  <template v-slot:indiNo="{ field, text, record }">
                    <span>{{ record.indiNo }}</span>
                  </template>
                  <!-- 指标名称 -->
                  <template v-slot:indiName="{ field, text, record }">
                    <span v-if="record.indiAttr === 'factor' && record.firstFlag"
                      >其中：{{ record.indiName }}</span
                    >
                    <span v-else-if="record.indiAttr === 'factor'" :class="$style.factor"
                      >{{ record.indiName }}
                    </span>
                    <span v-else :class="record.indiAttr === 'monitor' ? $style.monitor : ''">{{
                      record.indiName
                    }}</span>
                  </template>
                  <!-- 监测单位 -->
                  <template v-slot:monitorDeptName="{ field, text, record }">
                    <span>{{ record.monitorDeptName }}</span>
                  </template>
                  <!-- 数据来源 -->
                  <template v-slot:dataFrom="{ field, text, record }">
                    <span>{{ record.dataFromName }}</span>
                  </template>
                  <!-- 系统参考值 -->
                  <template v-slot:guideVal="{ field, text, record }">
                    <span
                      v-if="
                        record.dataFrom === 'system' &&
                          record.guideVal &&
                          record.guideVal !== 'null'
                      "
                      >{{ record.guideVal }}</span
                    >
                    <span v-else>--</span>
                  </template>
                  <!-- 指标结果值 -->
                  <template v-slot:indiResult="{ field, text, record }">
                    <div v-if="record.indiAttr === 'monitor' && record.dataFrom === 'calculate'">
                      <span v-if="record.indiResult">{{ record.indiResult }}</span>
                      <span v-else>--</span>
                    </div>
                    <div v-else>
                      <a-input
                        v-if="editable"
                        v-model="record.indiResult"
                        @blur="calIndiResult(record)"
                      ></a-input>

                      <span v-else>{{ record.indiResult }}</span>
                    </div>
                  </template>
                  <!-- 数据值单位 -->
                  <template v-slot:indiUnit="{ field, text, record }">
                    <span>{{ record.indiUnitName }}</span>
                  </template>
                  <!-- 修改说明 -->
                  <template v-slot:editDesc="{ field, text, record }">
                    <span v-if="record.indiAttr === 'monitor' && record.dataFrom === 'calculate'">
                      --
                    </span>
                    <a-input v-else-if="editable" v-model="record.editDesc"></a-input>
                    <span v-else>{{ record.editDesc }}</span>
                  </template>
                  <!-- 预警状态 -->
                  <template v-slot:alertStatus="{ field, text, record }">
                    <span v-if="record.indiAttr === 'factor'">--</span>
                    <div v-else>
                      <div
                        v-if="!record.alertStatus || 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>
                </xm-child-table>
              </template>
            </sd-form-item-td>
          </tr>

          <!-- 任务来源 -->
          <sd-form-item-td :hidden="true" name="taskFrom" />
        </table>
      </template>
    </sd-webflow>
  </div>
</template>

<script>
import { Message } from 'ant-design-vue'
import KpiService from '../kpi-service'
import components from './_import-components/kpi-indi-task-form-import'

export default {
  name: 'KpiIndiTaskForm',
  metaInfo: {
    title: '指标报送任务',
  },
  components: {
    ...components,
  },
  data() {
    return {
      sysFlag: false,
      btnName: '',
      loading: false,
      childColumns: [
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'indiId', sdHidden: true },
        { dataIndex: 'indiAttr', sdHidden: true },
        { dataIndex: 'indiNo', title: '指标编码' },
        { dataIndex: 'indiName', title: '指标名称' },
        { dataIndex: 'monitorDeptCode', sdHidden: true },
        { dataIndex: 'monitorDeptName', title: '监测单位' },
        { dataIndex: 'monitorDeptId', title: '监测单位ID', sdHidden: true },
        { dataIndex: 'dataFrom', title: '数据来源' },
        { dataIndex: 'guideVal', title: '系统参考值' },
        { dataIndex: 'indiResult', title: '指标结果值' },
        { dataIndex: 'indiUnit', title: '数据值单位' },
        { dataIndex: 'editDesc', title: '修改说明' },
        { dataIndex: 'alertStatus', title: '预警状态' },
        { dataIndex: 'indiFrequency', sdHidden: true },
        { dataIndex: 'parentIndiId', sdHidden: true },
        { dataIndex: 'year', sdHidden: true },
        { dataIndex: 'dataPeriod', sdHidden: true },
        { dataIndex: 'uuid', sdHidden: true },
      ],
    }
  },
  mounted() {
    // 获取子表数据
    const id = this.$refs.flow.getFieldValue('id')
    this.getDetailList(id)
  },
  methods: {
    actionBtnClick(evt, { button, FlowData }) {
      // 记录点击按钮的名称
      this.btnName = button.fakeId
    },
    saveproject(formdata) {
      if (this.btnName === 'save') {
        // 保存成功后调用接口更新子表数据
        const id = formdata.processFormData.processFormPropertyValues?.find(
          (item) => item.name === 'id'
        )
        this.getDetailList(id.value)
      }
    },
    getDetailList(id) {
      // 获取指标报送任务明细
      KpiService.findTaskDetailList(id)
        .then((res) => {
          if (res) {
            res.forEach((item, index) => {
              // 首项因子指标增加标记位
              if (
                item.indiAttr === 'factor' &&
                res[index - 1] &&
                res[index - 1].indiAttr === 'monitor' &&
                res[index - 1].dataFrom === 'calculate'
              ) {
                item.firstFlag = true
              }
              // 系统集成标记位
              if (item.dataFrom === 'system') {
                this.sysFlag = true
              }
            })
            // 子表赋值
            this.$refs.flow.setFieldValue('indiTaskDetailList', res)
          }
        })
        .catch((err) => {
          // eslint-disable-next-line no-console
          console.log(err)
          Message.error('出错了，请联系管理员', 1)
        })
    },
    calGuideVal() {
      // 重新计算系统参考值
      this.loading = true
      const id = this.$refs.flow.getFieldValue('id')
      KpiService.getResetGuideVal(id)
        .then((res) => {
          if (res && res[0]) {
            const detail = this.$refs.flow.getFieldValue('indiTaskDetailList') // 子表数据
            res.forEach((item) => {
              if (item.guideVal === 'queryFailed') {
                throw new Error(`queryFailed`)
              }
              // 筛选同id同监测单位的子表数据
              const dtemp = detail.find(
                (ditem) => ditem.id === item.id && ditem.monitorDeptId === item.monitorDeptId
              )
              if (dtemp) {
                // 系统参考值赋值
                dtemp.guideVal = item.guideVal
              }
            })
            // 更新子表数据
            this.$refs.flow.setFieldValue('indiTaskDetailList', detail)
            Message.success('重新计算系统参考值成功')
          } else {
            Message.error('重新计算失败')
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
          if (err.message === 'queryFailed') {
            Message.error('数据库查询失败')
          } else {
            Message.error('出错了，请联系管理员')
          }
        })
    },
    calIndiResult(record) {
      // 校验是否输入数字
      if (record.indiResult && !isNaN(record.indiResult)) {
        // 数据值单位是 % 元 美元 时，保留2位小数
        if (
          record.indiUnitName === '%' ||
          record.indiUnitName === '元' ||
          record.indiUnitName === '美元'
        ) {
          record.indiResult = parseFloat(record.indiResult).toFixed(2)
        }
      } else {
        record.indiResult = ''
      }
      // 计算指标结果值,预警状态
      const id = this.$refs.flow.getFieldValue('id') // 主键id
      const detail = this.$refs.flow.getFieldValue('indiTaskDetailList')

      // 筛选同单位同主指标ID的因子指标
      const indisArr = detail?.filter((ditem) => {
        return (
          ditem.parentIndiId === record.parentIndiId &&
          ditem.monitorDeptCode === record.monitorDeptCode &&
          ditem.indiAttr === 'factor'
        )
      })
      // 接口参数赋值
      const data = []
      if (indisArr.length > 0) {
        indisArr?.forEach((res) => {
          if (res.parentIndiId === record.parentIndiId) {
            data.push({
              id: res.id,
              parentIndiId: res.parentIndiId,
              indiId: res.indiId,
              taskId: res.taskId,
              indiResult: res.indiResult,
              monitorDeptId: res.monitorDeptId,
              monitorDeptCode: res.monitorDeptCode,
              monitorDeptName: res.monitorDeptName,
              indiFrequency: res.indiFrequency,
            })
          } else {
            data.push({
              id: record.id,
              parentIndiId: record.parentIndiId,
              indiId: record.indiId,
              taskId: record.taskId,
              indiResult: record.indiResult,
              monitorDeptId: record.monitorDeptId,
              monitorDeptCode: record.monitorDeptCode,
              monitorDeptName: record.monitorDeptName,
              indiFrequency: record.indiFrequency,
            })
          }
        })
      } else {
        data.push({
          id: record.id,
          parentIndiId: record.parentIndiId,
          indiId: record.indiId,
          taskId: record.taskId,
          indiResult: record.indiResult,
          monitorDeptId: record.monitorDeptId,
          monitorDeptCode: record.monitorDeptCode,
          monitorDeptName: record.monitorDeptName,
          indiFrequency: record.indiFrequency,
        })
      }

      const redata = {
        taskId: id,
        result: data,
      }
      KpiService.getIndiResult(redata)
        .then((res) => {
          if (res) {
            // 筛选对应主指标，预警状态赋值
            const monitorIndi = detail.find(
              (item) => item.id === parseInt(res.id) && item.monitorDeptId === res.monitorDeptId
            )
            if (monitorIndi) {
              if (
                record.indiUnitName === '%' ||
                record.indiUnitName === '元' ||
                record.indiUnitName === '美元'
              ) {
                // 数据值单位是元和%和美元的保留2位小数
                if (res.indiResult && !isNaN(res.indiResult)) {
                  monitorIndi.indiResult = parseFloat(res.indiResult).toFixed(2) // 指标结果值
                }
              } else {
                if (res.indiResult && !isNaN(res.indiResult)) {
                  monitorIndi.indiResult = res.indiResult // 指标结果值
                }
              }
              monitorIndi.alertStatus = res.alertStatus // 预警状态
            }
            // 更新子表数据
            this.$refs.flow.setFieldValue('indiTaskDetailList', detail)
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
          // eslint-disable-next-line no-console
          console.log(err)
          Message.error('出错了，请联系管理员')
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.flowform {
  .btnselect {
    position: relative;
    top: 4px;
    float: right;
    .batchselect {
      z-index: 100;
      margin-left: 10px;
    }
  }
  .monitor {
    font-weight: bolder;
  }
  .factor {
    padding-left: 30px;
  }
  :global .ant-form-item-children {
    .ant-table colgroup > col.ant-table-selection-col {
      width: 0;
    }
    .ant-checkbox-wrapper {
      display: none;
    }
    .ant-table-row:hover .handle_sd-draggable_common::before {
      display: none;
    }
    .anticon-setting {
      display: none;
    }
  }
  .status {
    width: 25px;
    height: 25px;
    background-color: #aaaaaa;
    color: #fff;
    padding-left: 4px;
    border-radius: 3px;
  }
  .redstatus {
    width: 25px;
    height: 25px;
    background-color: #fb0606;
    color: #fff;
    padding-left: 4px;
    border-radius: 3px;
  }
  .ystatus {
    width: 25px;
    height: 25px;
    background-color: #fff600;
    color: #fff;
    padding-left: 4px;
    border-radius: 3px;
  }
  .lstatus {
    width: 25px;
    height: 25px;
    background-color: #8dcb98;
    color: #fff;
    padding-left: 4px;
    border-radius: 3px;
  }
}
</style>
