<template>
  <span>
    <audit-form-top-banner
      :handel-save-form="saveForm"
      :form-data="mode"
      @handelSaveForm="saveForm"
    >
      <sd-detail-form
        ref="docform"
        page-id="ic/defect/statement/icDefectList"
        :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
        :class="$style.form"
        :read-only="mode === 'VIEW' ? true : false"
        @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="expandA"
                  :expand-str="'expandA'"
                  :group-label="'基本信息'"
                  tablestyle="''"
                  @changedClick="changedClick"
                ></audit-advanced-group> </td></tr
          ></table>

          <table v-show="expandA">
            <tr v-show="false"><sd-form-item-td name="rectStatus"></sd-form-item-td></tr>
            <tr>
              <!-- 评价名称 -->
              <sd-form-item-td name="evaluationName"> </sd-form-item-td>
              <!-- 控制所属组织 -->
              <sd-form-item-td :hidden="true" name="controOrgCode" />
              <sd-form-item-td name="controOrgOpt">
                <!-- <sd-group-picker
                  v-model="model.controOrgOpt"
                  :root-node="rootNode"
                  :hierarchical="false"
                  :single="true"
                  @change="deptchange"
                /> -->
                <audit-group-picker
                  v-model="model.controOrgOpt"
                  :single="true"
                  :selectall="false"
                  :read-only="false"
                  :root-node="rootNode"
                  :top-node-text="'内控机构'"
                  :treeparams="{
                    moduleId: 'icMtxVersion',
                  }"
                  @change="deptchange"
                />
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 流程名称 -->
              <sd-form-item-td name="prcName">{{ model.prcName }}</sd-form-item-td>
              <!-- 控制点名称 -->
              <sd-form-item-td name="measureName">
                <a-input v-model="model.measureName" style="width:calc(100% - 80px);" read-only />
                <span style="padding:5px">
                  <a-button @click="showflpath">选择</a-button>
                </span>
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 控制点编号 -->
              <sd-form-item-td name="measureCode">{{ model.measureCode }}</sd-form-item-td>
              <!-- 测试结果 -->
              <sd-form-item-td name="testResult" component="a-select" />
            </tr>
            <tr>
              <!-- 缺陷类型 -->
              <sd-form-item-td name="defectType" component="a-select" />
              <!-- 缺陷等级 -->
              <sd-form-item-td name="defectLevel" component="a-select" />
            </tr>
            <tr>
              <!-- 缺陷责任组织 -->
              <sd-form-item-td name="liabilityOrgOpt" />
              <!-- 录入方式 -->
              <sd-form-item-td v-if="initParam(model)" name="entryMethod">
                {{ model.entryMethod }}</sd-form-item-td
              >
            </tr>
          </table>
        </template>
      </sd-detail-form>
    </audit-form-top-banner>
    <ic-measure-select
      ref="mtxmeasuresel"
      :version-id="versionId"
      :single="true"
      :org-id="orgId + ''"
      :org-name="orgName"
      :selected-keys="[]"
      @fnqd="fnqd"
    />
  </span>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import { Modal, Message } from 'ant-design-vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import axios from '@/common/services/axios-instance'
import auditGroupPicker from '@product/iam/components/picker/audit-group-picker.vue'
import icMeasureSelect from '../../../components/ic-measure-select.vue'
import auditFormTopBanner from '../../../components/audit-form-top-banner'
import auditAdvancedGroup from '../../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../../components/audit-advanced-group-mixins'
import MtxProcessService from '../../mtxprocess/mtx-process-service'
import components from './_import-components/ic-defect-statement-form-import'

export default {
  name: 'IcDefectStatementForm',
  metaInfo: {
    title: '缺陷清单表单',
  },
  components: {
    ...components,
    auditFormTopBanner,
    auditAdvancedGroup,
    icMeasureSelect,
    auditGroupPicker,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      entryMethod: '录入',
      expandA: true,
      mode: null,
      versionId: null,
      orgId: null,
      orgName: '',
      rootNode: {},
      flag: true,
    }
  },
  mounted() {
    let userInfo = getUserInfo()
    const params = {
      orgId: userInfo.deptId,
      moduleId: 'icMtxVersion',
    }
    axios({
      url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
      method: 'get',
    }).then((res) => {
      userInfo = res.data
      params.orgId = res.data.id
      axios({
        url: 'api/xcoa-mobile/v1/iamorg/findIamOrgId',
        method: 'post',
        params,
      }).then((res1) => {
        // this.id = res.data
        const deptCode = userInfo.id.toString()
        const deptName = userInfo.name
        this.rootNode = { code: res1.data, name: deptName, id: res1.data }
        this.orgName = deptName
      })
    })
    if (this.$route.query.versionId) {
      this.versionId = parseInt(this.$route.query.versionId)
    }
  },
  methods: {
    deptchange(val) {
      if (val) {
        this.orgId = null
        this.versionId = null
        // 根据组织ID获取到机构ID
        const params = {
          orgId: val[0].code,
          moduleId: 'icMtxVersion',
        }
        this.orgName = val[0].name
        this.orgId = val[0].oldId
        MtxProcessService.getversion(this.orgId).then((res) => {
          if (res.data.id) {
            this.versionId = res.data.id.toString()
          }
        })
        this.$refs.docform.setFieldValue('controOrgCode', val[0].oldId.toString())
      }
    },
    fnqd(data) {
      if (data.length !== 1) {
        return false
      } else {
        axios({
          url: 'api/framework/v1/page/wp/ic/measure/icMtxMeasure?id=' + data[0].toString(),
          method: 'get',
        }).then((res) => {
          const measureName = res.data.pageFormData.pageFieldInfos.findIndex(
            (i) => i.name === 'measureName'
          )
          const measureCode = res.data.pageFormData.pageFieldInfos.findIndex(
            (i) => i.name === 'measureCode'
          )
          const mtxPrcId = res.data.pageFormData.pageFieldInfos.findIndex(
            (i) => i.name === 'mtxPrcId'
          )
          this.$refs.docform?.setFieldValue(
            'measureName',
            res.data.pageFormData.pageFieldInfos[measureName].value
          )
          this.$refs.docform?.setFieldValue(
            'measureCode',
            res.data.pageFormData.pageFieldInfos[measureCode].value
          )

          this.getpath(res.data.pageFormData.pageFieldInfos[mtxPrcId].value).then((d) => {
            this.$refs.docform?.setFieldValue('prcName', d)
          })
        })
      }
    },
    initParam(model) {
      if (this.flag) {
        if (this.$route.query.record && this.$route.query.record !== '') {
          this.orgId = model.controOrgCode
          if (model.entryMethod !== '转入') {
            MtxProcessService.getversion(this.orgId).then((res) => {
              if (res.data.id) {
                this.versionId = res.data.id.toString()
              }
            })
          }
        } else {
          model.controOrgOpt = []
          model.liabilityOrgOpt = []
          model.entryMethod = this.entryMethod
          model.rectStatus = '01'
        }
        this.flag = false
      }
      return true
    },
    getpath(id) {
      return new Promise((resolve, reject) => {
        MtxProcessService.findupcatinfo(id).then((res) => {
          resolve(res.data)
        })
      })
    },
    showflpath() {
      if (this.versionId) {
        this.$refs.mtxmeasuresel.showtree()
      } else {
        Modal.info({
          content: '请联系管理员配置' + this.orgName + '所属机构',
        })
      }
    },
    // 页面加载完成后
    sdFormReady() {
      this.mode = this.$refs.docform.formData.mode
      // 如果是转入，则直接是VIEW
      const index = this.$refs.docform.formData.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'entryMethod'
      )
      const zgid = this.$refs.docform.formData.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'rectRequireId'
      )
      if (this.$refs.docform.formData.pageFormData.pageFieldInfos[index].value === '转入') {
        this.mode = 'VIEW'
      } else if (
        this.$refs.docform.formData.pageFormData.pageFieldInfos[zgid].value !== undefined &&
        this.$refs.docform.formData.pageFormData.pageFieldInfos[zgid].value !== null
      ) {
        this.mode = 'VIEW'
      } else {
        const createname = this.$refs.docform.formData.pageFormData.pageFieldInfos.findIndex(
          (i) => i.name === 'creatorName'
        )
        if (
          this.$refs.docform.formData.pageFormData.pageFieldInfos[createname].value !==
          getUserInfo().name
        ) {
          this.mode = 'VIEW'
        }
        if (!this.mode) {
          this.mode = this.$route.query.mode
        }
      }
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    saved() {
      Message.success({ content: '保存成功！' }, 1).then(() => {
        this.close(true)
      })
    },
    // 保存
    saveForm() {
      this.$refs.docform.validateFields().then((valid) => {
        if (valid) {
          var opt = this.$refs.docform.getFieldValue('controOrgOpt')
          if (opt !== undefined) {
            opt[0].type = 'Group'
            this.$refs.docform.setFieldValue('controOrgOpt', opt)
          }
          this.$refs.docform.saveBtnClick()
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';

.btnselect {
  position: relative;
  top: 4px;
  right: 200px;
  float: right;
  .batchselect {
    z-index: 100;
    margin-left: 10px;
  }
}
.tablexm tr td {
  border: none !important;
}
</style>
