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

        <table v-show="templateExpand">
          <tr>
            <!-- 模板名称 -->
            <sd-form-item-td name="templateName">
              <a-form-model-item
                :rules="[
                  {
                    validator: validator,
                    trigger: ['change', 'blur'],
                  },
                ]"
                prop="templateName"
              >
                <a-input v-model="model.templateName"></a-input
              ></a-form-model-item>
            </sd-form-item-td>
            <!-- 模板类型 -->
            <sd-form-item-td v-if="mode === 'VIEW'" name="templateType" />
            <sd-form-item-td v-else name="templateType">
              <template v-slot:read-and-edit="{ editable }">
                <a-select
                  v-model="model.templateType"
                  :allow-clear="true"
                  :options="fields.templateType.attr.selectListItem"
                  @change="typeChange"
                ></a-select>
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td
              v-if="(mode === 'VIEW') | (isfalse === true)"
              :input-props="{ disabled: isfalse }"
              name="isDefault"
            />
            <sd-form-item-td v-else name="isDefault">
              <template v-slot:read-and-edit="{ editable }">
                <a-radio-group v-model="model.isDefault" @change="ischange(model)">
                  <a-radio
                    v-for="(v, index) in fields.isDefault.attr.selectListItem"
                    :key="index"
                    :allow-clear="true"
                    :value="v.value"
                    @click="fnRadioChange"
                    >{{ v.label }}</a-radio
                  >
                </a-radio-group>
              </template>
            </sd-form-item-td>

            <sd-form-item-td :hidden="model.isDefault !== '0'" name="rangeDeptMember">
              <template v-slot:read-and-edit="{ editable }">
                <span v-if="editable">
                  <AuditGroupPicker
                    v-model="model.rangeDeptMember"
                    :single="false"
                    :read-only="false"
                    :root-node="rootNode"
                    :selectall="rootNode === undefined ? true : false"
                    :top-node-text="rootNode === undefined ? '审计机构库' : ''"
                    :treeparams="
                      rootNode === undefined
                        ? {
                            formId: 'IAM_ORG',
                            idColumnId: 'id',
                            nameColumnId: 'org_name',
                            parentColumnId: 'parent_id',
                            otherColumnId: ['org_id', 'creation_time'],
                            configId: '11',
                          }
                        : {}
                    "
                  />
                </span>
                <span v-else>
                  {{ fields.rangeDeptMember.attr.displayValue }}
                </span>
              </template>
            </sd-form-item-td>
          </tr>

          <tr>
            <!-- 模板说明 -->
            <sd-form-item-td name="templateDesc" :colspan="3">
              <a-textarea v-model="model.templateDesc" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 编制人员 -->
            <sd-form-item-td name="authName" />
            <!-- 编制日期 -->
            <sd-form-item-td name="authTime" />
          </tr>
          <tr>
            <!-- 附件 -->
            <sd-form-item-td v-if="initparams(model)" name="attachment" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <sd-attachment
                  :key="key"
                  ref="attch"
                  v-model="model.attachment"
                  :read-only="editable !== true"
                  :max="1"
                  :accept="acceptType"
                  :group-id="JSON.parse(fields.attachment.value).value"
                >
                </sd-attachment>
              </template>
            </sd-form-item-td>
          </tr>
        </table>
      </template>
    </sd-detail-form>
  </audit-form-top-banner>
</template>

<script>
import { Message } from 'ant-design-vue'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
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 AuditGroupPicker from '../../components/picker/audit-group-picker.vue'
import components from './_import-components/audit-template-form-import'

export default {
  name: 'AuditTemplateForm',
  metaInfo: {
    title: '审计模板库',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    AuditGroupPicker,
    auditFormTopBanner,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      mode: null,
      readOnly: false,
      key: 0,
      isfalse: false,
      saveFlag: true,
      templateExpand: true,
      rootNode: {},
      acceptType: '',
      templateType: '',
    }
  },
  created() {
    let userInfo = getUserInfo()
    getUserInfo().roles.find((item) => {
      if (item.code === 'ADMINISTRATOR') {
        return (this.rootNode = { code: 0, name: '审计机构库', id: 0 })
      } else {
        const params = {
          orgId: userInfo.deptId,
        }
        axios({
          url: 'api/xcoa-mobile/v1/iamorg/getUserGroup',
          method: 'get',
        }).then((res) => {
          userInfo = res.data
          params.orgId = res.data.id
          axios({
            url: 'api/xcoa-mobile/v1/iamorg/findIamOrgId',
            method: 'post',
            params,
          }).then((res) => {
            this.id = res.data
            const deptCode = userInfo.id.toString()
            const deptName = userInfo.name
            this.rootNode = { code: deptCode, name: deptName, id: this.id }
          })
        })
      }
    })
  },
  mounted() {
    const ini = setInterval(() => {
      if (
        this.$refs.docform &&
        (this.$refs.docform.$refs.form || this.$refs.docform.$refs.sdForm)
      ) {
        clearInterval(ini)
        // const userInfo = getUserInfo()
        // const authName = this.$refs.docform.getFieldValue('authName')
        // if (authName !== userInfo.name) {
        //   this.mode = 'VIEW'
        //   this.readOnly = true
        // } else {
        this.mode = this.$refs.docform.formData.mode
        if (this.mode === 'VIEW') {
          this.readOnly = true
        }
        // 加载时如果默认为否，则设置适用机构范围为必填
        const isDefault = this.$refs.docform.formData.pageFormData.pageFieldInfos.find((item) => {
          return item.name === 'isDefault'
        }).value
        if (isDefault === '1') {
          this.fnRadioChange({ currentTarget: { value: '1' } })
        } else {
          this.fnRadioChange({ currentTarget: { value: '0' } })
        }
        // }
      }
    }, 100)
  },
  methods: {
    fnRadioChange(e) {
      const val = e.currentTarget.value
      if (val === '1') {
        this.$refs.docform.formData.pageFormData.pageFieldInfos.find((item) => {
          return item.name === 'rangeDeptMember'
        }).required = false
      } else {
        this.$refs.docform.formData.pageFormData.pageFieldInfos.find((item) => {
          return item.name === 'rangeDeptMember'
        }).required = true
      }
    },
    // 页面加载完成后
    sdFormReady() {},
    ischange(model) {
      const value = this.$refs.docform.getFieldValue('isDefault')
      if (value === '1') {
        this.$refs.docform.setFieldValue('rangeDeptMember', null)
        model.rangeDeptMember = null
      }
    },

    initparams(model) {
      // axios({
      //   url: 'api/xcoa-mobile/v1/iamorg/getAccountGroup',
      //   method: 'get',
      // }).then((res) => {
      //   if (res.data === true) {
      //     this.isfalse = false
      //   } else {
      //     this.isfalse = true
      //     if (model.id === undefined) {
      //       model.isDefault = '0'
      //     }
      //   }
      // })
      const value = model.templateType
      if (value === '01' || value === '04') {
        this.acceptType = '.xls,.xlsx'
      } else if (value === '07') {
        // 其他
        this.acceptType =
          '.xls,.xlsx,.doc,.docx,.pdf,.ofd,.jpg,.png,.gif,.bmp,.txt,.text,.ppt,.pptx,.zip,.rar,.7z'
      } else {
        this.acceptType = '.doc,.docx'
      }
      return true
    },
    // 类型变化时
    typeChange() {
      const attch = this.$refs.attch.value
      if (attch.length > 0) {
        const groupId = JSON.parse(
          this.$refs.docform.formData.pageFormData.pageFieldInfos.find(
            (item) => item.name === 'attachment'
          ).value
        ).value
        attch.forEach((item) => {
          axios.delete(`api/xcoa-mobile/v1/attachment-extend/attachments-delete/` + groupId, {
            params: {
              attachmentId: item.Unid,
              formId: '',
              beanId: '',
              instId: 0,
              lockId: this.lockId,
            },
          })
        })
        this.key = this.key + 1
        this.$refs.attch.getFileList()
      }
    },
    validator(rule, value, callback) {
      value = encodeURIComponent(value)
      const id = this.$route.query.record || ''
      debounce(() => {
        axios
          .get(`api/xcoa-mobile/v1/iamtemplate/template-name?templateName=${value}&id=` + id)
          .then((res) => {
            if (res?.data === true) {
              callback()
            } else {
              callback('已存在，不允许重复')
            }
          })
      }, 500)()
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    // 保存
    saveForm() {
      this.$refs.docform.validateFields().then(() => {
        Message.success('保存成功').then(() => {
          this.$refs.docform.saveBtnClick()
        })
      })
    },
    saved() {
      this.close(true)
    },
  },
}
</script>

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