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

        <table v-show="templateExpand">
          <tr style="display:none">
            <!-- 模型编号 -->
            <sd-form-item-td name="auditOrgId" />
          </tr>
          <tr>
            <!-- 模型编号 -->
            <sd-form-item-td name="modelCode" label="模型编号" :input-props="{ disabled: true }">
              <!-- {{ model.id }} -->
            </sd-form-item-td>

            <!-- 模型名称 -->
            <sd-form-item-td name="modelName">
              <a-form-model-item
                :rules="[
                  {
                    validator: validatorModelName,
                    trigger: ['blur'],
                  },
                ]"
                prop="modelName"
              >
                <a-input v-model="model.modelName" />
              </a-form-model-item>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 模型类型 new -->
            <sd-form-item-td
              v-if="modelTypeFocus(fields.modelType.attr.selectListItem, 'init')"
              name="modelType"
            >
              <a-select
                v-model="model.modelType"
                @change="modelTypeChange"
                @focus="modelTypeFocus(fields.modelType.attr.selectListItem)"
              >
                <a-select-option
                  v-for="(item, i) in fields.modelType.attr.selectListItem"
                  :key="i"
                  :value="item.value"
                  >{{ item.label }}</a-select-option
                >
              </a-select>
            </sd-form-item-td>
            <!-- 事件标签 -->
            <sd-form-item-td name="eventTag" label="事件标签分类">
              <a-select v-model="model.eventTag" @change="eventChange">
                <a-select-option v-for="(item, i) in eventList" :key="i" :value="item.id">{{
                  item.tagName + '-' + item.id
                }}</a-select-option>
              </a-select>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 整改截至时间 ， 状态-->
            <sd-form-item-td name="reformTime">
              <div class="reform-time-maintain-from">
                <a-input-number
                  v-model="model.reformTime"
                  :min="minSize"
                  :disabled="model.modelType !== '1'"
                  class="reform-time-data"
                ></a-input-number>
                <sd-form-item name="reformTimeType" label=""></sd-form-item>
              </div>
            </sd-form-item-td>
            <sd-form-item-td name="lineStatus" label="状态">
              <a-radio-group v-model="model.lineStatus" :disabled="true">
                <a-radio
                  v-for="item in fields.lineStatus.attr.selectListItem"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.label }}</a-radio
                >
              </a-radio-group>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 模型领域， 模型阶段 -->
            <sd-form-item-td name="modelDomain">
              <a-select v-model="model.modelDomain" :disabled="true" @change="areaChange">
                <a-select-option v-for="(item, i) in areaOption" :key="i" :value="item.id">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </sd-form-item-td>
            <sd-form-item-td name="modelPhase">
              <a-select v-model="model.modelPhase" @change="stageChange">
                <a-select-option v-for="(item, i) in stageOption" :key="i" :value="item.id">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- jmId jmTable -->
            <sd-form-item-td name="jmId" />
            <sd-form-item-td name="jmTable" />
          </tr>
          <tr>
            <sd-form-item-td name="viewAddress">
              <!-- 查看按钮 -->
              <a-button type="primary" :disabled="!model.jmId" @click="onViewJm(model.jmId)"
                >查看</a-button
              >
              <span v-if="!model.jmId" :class="$style.tips">（请先输入建木ID）</span>
            </sd-form-item-td>
            <!-- <sd-form-item-td name="editAddress" /> -->
          </tr>
          <!-- <tr>
            是否追责
            <sd-form-item-td v-if="model.modelType === '1'" name="isAccountable" />
          </tr> -->

          <tr>
            <sd-form-item-td v-if="model.modelType === '1'" name="reformDesc">
              <a-textarea v-model="model.reformDesc" :rows="3" />
            </sd-form-item-td>
            <sd-form-item-td name="risk" label="风险描述">
              <a-textarea v-model="model.risk" :rows="3" />
            </sd-form-item-td>
          </tr>
          <sd-form-item-td v-if="initParam(model)" :hidden="true" name="catalogId" />
        </table>
      </template>
    </sd-detail-form>
  </audit-form-top-banner>
</template>

<script>
import { Message } from 'ant-design-vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
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 components from './_import-components/audit-maintain-from-import'
import auditMaintainService from './audit-maintain-service'
import sdFormItem from '@/common/components/sd-form-item.vue'
import auditModelService from '../model/audit-model-service'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'

export default {
  name: 'AuditMaintainFrom',
  metaInfo: {
    title: '审计模型',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    auditFormTopBanner,
    sdFormItem,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      templateExpand: true,
      orgId: '',
      eventList: [],
      // 模型领域 ，模型阶段
      areaOption: [],
      stageOption: [],

      // 名称
      optionSelect: {
        area: '',
        stage: '',
        event: '',
      },
      // 时间类型
      eventClassOption: [],

      // 是否追责
      isAccountable: false,
      // 刷新表单
      key: 0,
      // 类型option
      typeOption: [],
      times: null,
      minSize: 0,
    }
  },
  computed: {
    isAddStatus() {
      return this.$route.query.record === undefined
    },
  },
  created() {
    this.getFormOption()
  },
  // 注销页面时
  beforeDestroy() {
    clearInterval(this.times)
  },
  methods: {
    // 模型名称校验
    validatorModelName(rule, value, callback) {
      value = encodeURIComponent(value)
      // 如果有模型id则传
      const modelId = this.$route.query.record ? `&id=${this.$route.query.record}` : ''
      const url = `api/xcoa-mobile/v1/iammodelmaintain/checkModelName?modelName=${value}` + modelId
      debounce(() => {
        axios.post(url).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback('已存在模型名称，不可以重复')
          }
        })
      }, 500)()
    },
    onViewJm(id) {
      if (!id) {
        Message.error({ content: '请填写建木ID' })
        return
      }
      auditModelService.getBuildUrl(id).then((res) => {
        if (res.data) {
          window.open(res.data)
        } else {
          Message.error({ content: '请填写正确的建木ID' })
        }
      })
    },
    getFormOption() {
      auditMaintainService.getEventTagList().then((res) => {
        this.eventList = res.data
      })
      auditMaintainService.getAreaListAll().then((res) => {
        this.areaOption = res.data

        const data = res.data.find((item) => item.id === parseInt(this.$route.query.modelDomain))
        // 确定元素加载成功后
        this.times = setInterval(() => {
          if (this.$refs.docform === undefined) return
          this.$refs.docform.setFieldValue('modelDomainName', data.name)
          this.$refs.docform.setFieldValue('modelDomain', data.id)
          clearInterval(this.times)
        }, 1000)
        // this.$refs.docform.setFieldValue('modelDomainName', data.name)
        // this.$refs.docform.setFieldValue('modelDomain', data.id)
      })
      auditMaintainService.getStageListAll().then((res) => {
        this.stageOption = res.data
      })
    },
    modelTypeChange(val) {
      this.isAccountable = val === '1'
      const name = this.typeOption.find((item) => item.value === val).label
      this.$refs.docform.setFieldValue('modelTypeName', name)
      // reformTime
      if (val !== '1') {
        this.$refs.docform.setFieldValue('reformTime', 0)
        this.minSize = 0
      } else {
        this.$refs.docform.setFieldValue('reformTime', 1)
        this.minSize = 1
      }
    },
    modelTypeFocus(filter, type) {
      this.typeOption = filter
      if (type === 'init') {
        this.$nextTick(() => {
          const val = this.$refs.docform.getFieldValue('modelType')
          const name = this.typeOption.find((item) => item.value === val).label
          this.$refs.docform.setFieldValue('modelTypeName', name)
          // 如果是空值
          const reformTime = this.$refs.docform.getFieldValue('reformTime')
          if (!reformTime) {
            this.$refs.docform.setFieldValue('reformTime', 0)
          }
        })
      }
      return true
    },
    areaChange(val) {
      // 根据val的值过滤选项
      this.optionSelect.area = this.areaOption.find((item) => item.id === val).name
    },
    stageChange(val) {
      this.optionSelect.stage = this.stageOption.find((item) => item.id === val).name
    },
    // 事件标签变化
    eventChange(val) {
      this.optionSelect.event = this.eventList.find((item) => item.id === val).tagName
    },

    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    // 保存
    saveForm() {
      // 是否增加名字
      const { area, stage, event } = this.optionSelect
      stage !== '' && this.$refs.docform.setFieldValue('modelPhaseName', stage)
      event !== '' && this.$refs.docform.setFieldValue('eventTagName', event)
      this.$refs.docform.setFieldValue('source', 0)
      // this.$refs.docform.setFieldValue('auditOrgId', 564)
      this.$refs.docform.validateFields().then(() => {
        // 过滤值为undefined的字段
        const data = this.$refs.docform.getFieldsValue()
        Object.keys(data).forEach((key) => {
          if (data[key] === undefined) {
            delete data[key]
          }
        })
        // this.$refs.docform.saveBtnClick()
        auditMaintainService.modelSaveGH(this.$refs.docform.getFieldsValue()).then((res) => {
          this.saved()
        })
      })
    },
    saved() {
      Message.success({ content: '保存成功！' }, 1).then(() => {
        this.close(true)
      })
    },
    initParam(model) {
      // 设置父id
      const { modelDomain } = this.$route.query
      // if (modelDomain) {
      //   this.times = setInterval(() => {
      //     if (this.areaOption.length === 0) return
      //     const data = this.areaOption.find((item) => item.id === modelDomain)
      //     console.log(
      //       '🚀 ~ file: audit-maintain-from.vue:291 ~ this.times=setInterval ~ data:',
      //       data
      //     )
      //     // model.modelDomainName = name
      //     // model.modelDomain = id
      //     clearInterval(this.times)
      //   }, 1000)
      // }
      return true
    },
  },
}
</script>

<style module lang="scss">
@import '@/webflow/sd-flow-form.scss';

.tips {
  margin-left: 10px;
}
</style>

<style>
.reform-time-maintain-from {
  display: flex;
}
.reform-time-data {
  margin-top: 4px;
}
</style>
