<template>
  <span>
    <sd-webflow
      ref="docform"
      :key="key"
      :validate-form="validForm"
      :removed-tabs="['sdRelatedDoc']"
      @actionBtnClick="actionBtnClick"
    >
      <template v-slot:form="{ model, fields, FlowData }">
        <table v-if="initData(model)">
          <colgroup>
            <col style="width: 15%;" />
            <col style="width: 35%;" />
            <col style="width: 15%;" />
            <col style="width: 35%;" />
          </colgroup>
          <tr v-show="false">
            <!-- 标题 -->

            <sd-form-item-td name="title" :colspan="3" />
          </tr>
          <tr>
            <td colspan="4" style="border:none">
              <audit-advanced-group
                :expand="expandJ"
                :expand-str="'expandJ'"
                :group-label="'风险审计信息'"
                @changedClick="changedClick"
              />
            </td>
          </tr>
          <tr v-show="expandJ">
            <!-- 业务编码 -->
            <sd-form-item-td name="businessCode" :input-props="{ disabled: true }" />
            <!-- 事件标签 -->
            <sd-form-item-td
              name="eventTagName"
              label="事件标签分类"
              :input-props="{ disabled: true }"
            />
          </tr>
          <!-- 模型编码 -->
          <!-- 模型名称 -->
          <tr v-show="expandJ">
            <sd-form-item-td name="batchName" :input-props="{ disabled: true }" />
            <sd-form-item-td name="batchCode" :input-props="{ disabled: true }" />
          </tr>

          <tr v-show="expandJ">
            <!-- 模型类型 -->
            <sd-form-item-td name="modelTypeName" :input-props="{ disabled: true }" />
            <!-- 整改人 -->
            <sd-form-item-td name="viewAccount" :input-props="{ disabled: true }" />
          </tr>
          <tr v-show="expandJ">
            <!-- 风险描述 -->
            <sd-form-item-td
              label="风险描述"
              name="risk"
              :colspan="3"
              :input-props="{ disabled: true }"
            />
          </tr>
          <tr v-if="isViewType">
            <td
              v-if="getClassdata(model, fields)"
              :colspan="4"
              style="line-height:40px;border:none1;"
              :class="$style.maintaintable"
            >
              <audit-advanced-group
                :expand="expandY"
                :expand-str="'expandY'"
                :group-label="'审计明细信息'"
                @changedClick="changedClick"
              >
                <template>
                  <sd-table
                    v-show="expandY"
                    ref="classtable"
                    :row-key="(record, index) => index"
                    :loading="false"
                    class="maintaintable"
                    :columns="childMXColumns"
                    :data-source="classdata"
                    :pagination="false"
                  >
                    <div slot="attachment" slot-scope="text, record">
                      <span :class="$style.exportClickBtn" @click="exportClick(record)">{{
                        record.fileName
                      }}</span>
                    </div>
                    <div slot="questionNature" slot-scope="text, record">
                      <a-select
                        v-model="record.questionNature"
                        placeholder="请选择问题性质"
                        allow-clear
                        @change="saveForm"
                      >
                        <a-select-option value="有业务无制度">有业务无制度</a-select-option>
                        <a-select-option value="有制度难执行">有制度难执行</a-select-option>
                        <a-select-option value="制度太宽泛缺乏操作细则"
                          >制度太宽泛缺乏操作细则</a-select-option
                        >
                        <a-select-option value="制度过时不具备可操作性"
                          >制度过时不具备可操作性</a-select-option
                        >
                        <a-select-option value="制度脱离实际难落地实施"
                          >制度脱离实际难落地实施</a-select-option
                        >
                        <a-select-option value="有制度未遵循">有制度未遵循</a-select-option>
                        <a-select-option value="特殊事项已经线下审批"
                          >特殊事项已经线下审批</a-select-option
                        >
                        <a-select-option value="事项紧急重目标轻合规"
                          >事项紧急重目标轻合规</a-select-option
                        >
                        <a-select-option value="制度理解存在人为偏差"
                          >制度理解存在人为偏差</a-select-option
                        >
                        <a-select-option value="工作疏忽未按制度行事"
                          >工作疏忽未按制度行事</a-select-option
                        >
                        <a-select-option value="人为规避制度管控要求"
                          >人为规避制度管控要求</a-select-option
                        >
                      </a-select>
                    </div>
                    <!-- <div slot="personResponsible" slot-scope="text, record">
                      <span :class="$style.exportClickBtn" @click="selectUserClick">{{
                        record.personResponsible || '请选择'
                      }}</span>
                    </div> -->
                  </sd-table>
                </template>
              </audit-advanced-group>
              <div v-show="false">
                <sd-dep-picker
                  ref="pRelSelect"
                  v-model="mainSendPersonal"
                  :single="true"
                  :read-only="false"
                  @change="changep"
                />
              </div>
            </td>
          </tr>
        </table>

        <template v-if="!isViewType">
          <tr>
            <td colspan="4" style="border:none">
              <audit-advanced-group
                :expand="expandDesc"
                :expand-str="'expandDesc'"
                :group-label="'整改说明'"
                @changedClick="changedClick"
              />
            </td>
          </tr>
          <table v-if="expandDesc">
            <sd-form-item-td name="reformDesc" :colspan="4">
              <a-textarea v-model="model.reformDesc" placeholder="请填写整改说明" :rows="3" />
            </sd-form-item-td>
          </table>
          <!-- 整改说明 -->
          <tr>
            <td colspan="4" style="border:none">
              <audit-advanced-group
                :expand="expandFiles"
                :expand-str="'expandFiles'"
                :group-label="'整改附件'"
                @changedClick="changedClick"
              />
            </td>
          </tr>
          <table v-if="expandFiles">
            <a-form-model-item label="">
              <div :class="$style.upload">
                <a-upload-dragger
                  :class="$style.uploadData"
                  name="RectificationFile"
                  :file-list="fileListTemp"
                  :accept="actualAccept"
                  :multiple="true"
                  :custom-request="(file) => customRequest(file, 0)"
                  @change="handleChange"
                >
                  <p class="ant-upload-drag-icon"><a-icon type="inbox"/></p>
                  <p class="ant-upload-text">请上传整改附件</p>
                </a-upload-dragger>
                <div :class="$style.uploadList">
                  <li v-for="(item, i) in fileList" :key="i">
                    <span>{{ item.name }}</span>
                    <!-- 删除 -->
                    <a-icon type="delete" style="cursor: pointer;" @click="deleteFile(i)" />
                  </li>
                </div>
              </div>
            </a-form-model-item>
          </table>
        </template>
        <!-- 整改说明 -->
      </template>
    </sd-webflow>
  </span>
</template>

<script>
import { Modal, Message } from 'ant-design-vue'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import components from './_import-components/audit-summarry-from-import'
import download from '@/common/services/download'
import { getUserInfo } from '@/common/store-mixin'
import moment from 'moment/moment'
import AuditRiskbraryService from './riskLibrary'
import { sdLocalStorage } from '@/common/services/storage-service'
import axios from '@/common/services/axios-instance'

// import
export default {
  name: 'AuditSummarryFrom',
  metaInfo: {
    title: '风险问题审计',
  },
  components: {
    ...components,
    auditAdvancedGroup,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      key: 0,

      // 控制是否展开
      expandY: true,
      expandJ: true,
      expandDesc: true,
      expandFiles: true,
      mainSendPersonal: [],
      fileList: [],
      fileListTemp: [],
      userInfo: getUserInfo(),
      childMXColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        // {
        //   title: '批次号',
        //   dataIndex: 'batchCode',
        // },
        // {
        //   title: '批次名称',
        //   dataIndex: 'batchName',
        // },

        {
          // 模型名称
          title: '模型名称',
          dataIndex: 'batchName',
        },
        {
          // 模型编号
          title: '模型编号',
          dataIndex: 'batchCode',
        },
        {
          title: '整改说明',
          dataIndex: 'reformDesc',
        },
        {
          title: '附件',
          dataIndex: 'attachment',
          scopedSlots: { customRender: 'attachment' },
        },
        {
          title: '问题性质',
          dataIndex: 'questionNature',
          width: '250px',
          scopedSlots: { customRender: 'questionNature' },
        },
        // {
        //   title: '问题责任人',
        //   dataIndex: 'personResponsible',
        //   scopedSlots: { customRender: 'personResponsible' },
        // },
      ],
      classIndexData: [],
      maintaindata: [],
      flag: true,
      modelFlag: true,
      classtable: false,
      // 分类列表
      classdata: [],
      // 基础数据
      baseData: {},
      isViewType: true,
      infoProperties: {},
      attachments: [],
      lockId: '',
      flagIs: true,
    }
  },
  computed: {
    actualAccept() {
      // 优先使用前端配置的类型限制，如未配置，则使用后端支持的类型
      return (
        this.accept || JSON.parse(sdLocalStorage.getItem('commonConfig') || '{}').attachType || ''
      )
    },
  },
  watch: {
    classdata() {
      this.saveForm()
    },
  },
  created() {
    const lock = sdLocalStorage.getItem(`Lock${this.webflow?.FlowData?.instId}`)
    this.lockId = (lock && JSON.parse(lock).sessionId) || ''
  },
  mounted() {
    this.initModelData()
  },
  methods: {
    initModelData() {
      if (!this.$route.query.extParams) return
      this.isViewType = false
      this.flagIs = false
      this.baseData = JSON.parse(this.$route.query.extParams)
      Object.keys(this.baseData).forEach((key) => {
        this.$refs.docform.setFieldValue(key, this.baseData[key])
      })
      // todo 问题整改人
      this.$refs.docform.setFieldValue('viewAccount', getUserInfo().name)
    },
    // 附件自定义上传
    customRequest(data, catnum = 0, item) {
      if (data.file.size === 0) {
        Message.warn(`不能上传大小为0的文件`)
        return
      }
      const file = {
        FileName: data.file.name,
        Completed: 0,
        CatNum: catnum,
      }

      this.attachments = [...this.attachments]
      const strTime = moment().format('YYYY-MM-DD HH:mm:ss')
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('FileName', data.file.name)
      formData.append('lockId', this.lockId)
      formData.append('groupId', this.groupId)
      Object.keys(this.infoProperties).forEach((key) => {
        formData.append(key, this.infoProperties[key])
      })

      formData.append(
        'querystring',
        `<file_unid></file_unid><file_name>${data.file.name}</file_name><file_size>${data.file.size}</file_size><completed>1</completed><file_create>${strTime}</file_create><file_update>${strTime}</file_update><file_editmodel>0</file_editmodel><file_lockuser>0</file_lockuser><CreateInfo>${this.userInfo.account} ${strTime}</CreateInfo><filetype></filetype><user_name>${this.userInfo.account}</user_name><UpdateInfo>${this.userInfo.account}于${strTime}创建.</UpdateInfo><TaodaInfo></TaodaInfo><CatNum>${catnum}</CatNum><Ext></Ext>`
      )
      const url = 'api/xcoa-mobile/v1/iam-attachment-extend/attachments-upload/indi'
      axios
        .post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
        .then((_) => {
          if (_.data.startsWith('false')) {
            Message.error(`${data.file.name} 上传失败`)
          } else {
            this.fileList.push({
              name: data.file.name,
              url: _.data,
            })

            const attachment = this.fileList.map((item) => item.url).join(',')
            const nameList = this.fileList.map((item) => item.name).join(',')

            this.$refs.docform.setFieldValue('attachment', attachment)
            this.$refs.docform.setFieldValue('fileName', nameList)

            data.onSuccess(_, data.file)
          }
        })
        .catch((e) => {
          Message.error(`${data.file.name} 上传失败`)
          throw e
        })
    },
    // 附件上传
    handleChange(info) {
      const status = info.file.status

      if (status === 'done') {
        Message.success(`${info.file.name} 上传成功.`)
      } else if (status === 'error') {
        Message.error(`${info.file.name} 上传失败.`)
      }
    },
    // <!-- 删除已上传附件 -->
    deleteFile(index) {
      this.fileList.splice(index, 1)
      const attachment = this.fileList.map((item) => item.url).join(',')
      const nameList = this.fileList.map((item) => item.name).join(',')
      this.$refs.docform.setFieldValue('attachment', attachment)
      this.$refs.docform.setFieldValue('fileName', nameList)
    },
    saveForm() {
      return new Promise((resolve) => {
        if (this.isViewType) {
          this.$refs.docform.setFieldValue('questionNature', this.classdata[0].questionNature)
          const account = getUserInfo().name
          const strTime = moment().format('YYYY-MM-DD')

          if (!this.classdata[0].checker) {
            this.$refs.docform.setFieldValue('checker', account)
          } else {
            this.$refs.docform.setFieldValue('reviewer', account)
          }
          if (!this.classdata[0].checkDate) {
            this.$refs.docform.setFieldValue('checkDate', strTime)
          } else {
            this.$refs.docform.setFieldValue('reviewDate', strTime)
          }
        }
        if (!this.isViewType) {
          const strTime = moment().format('YYYY-MM-DD')
          this.$refs.docform.setFieldValue('reformDate', strTime)

          this.$refs.docform.setFieldValue('title', getUserInfo().name + '风险审核')
        }
        resolve(true)
      })
    },
    validForm(e) {
      return Promise.resolve(true)
    },
    actionBtnClick(evt, { button, FlowData }) {
      if (button.buttonId === 'G_1_FXWTSJ.4') {
        if (!this.classdata[0]?.questionNature && this.isViewType) {
          evt.preventDefault()
          return Modal.warning({
            title: '提示',
            content: '请选择需要问题性质!',
          })
        }
      }
      if (button.fakeId === 'save' || button.fakeId === 'workflow-push') {
        // 保存前先校验计划是否已经存在
        evt.waitUntil(
          new Promise((resolve, reject) => {
            this.saveForm(button.buttonId).then((res) => {
              if (!res) {
                evt.preventDefault()
              }
              resolve()
            })
          })
        )
      }
    },
    initData(model) {
      // 如果整改人是自己则可以上传
      if (model.viewAccount === getUserInfo().name) {
        this.isViewType = false
        if (model.attachment && this.flagIs) {
          const attachmentList = model.attachment.split(',')
          const fileNameList = model.fileName.split(',')
          this.fileList = []
          for (let i = 0; i < attachmentList.length; i++) {
            this.fileList.push({
              name: fileNameList[i],
              url: attachmentList[i],
            })
          }
          this.flagIs = false
        }
      }
      return true
    },
    getClassdata(model, fields) {
      if (this.flag) {
        this.classdata = [
          {
            batchCode: fields.batchCode.value,
            batchName: fields.batchName.value,
            reformDesc: fields.reformDesc.value,
            attachment: fields.attachment.value,
            fileName: fields.fileName.value,
            questionNature: fields.questionNature.value || undefined,
            // personResponsible: fields.personResponsible.value,
            checker: fields.checker.value,
            checkDate: fields.checkDate.value,
            reviewer: fields.checker.value,
            reviewDate: fields.checkDate.value,
          },
        ]
        this.flag = false
      }
      return true
    },
    // 下载
    exportClick(row) {
      const attachmentList = row.attachment.split(',')
      const fileNameList = row.fileName.split(',')
      for (let i = 0; i < attachmentList.length; i++) {
        const spliceIndex = attachmentList[i].lastIndexOf('|')
        const destStep = attachmentList[i].substring(spliceIndex + 1, attachmentList[i].length)
        download(
          'api/framework/v1/task-form-process/download-attachments/' + destStep,
          fileNameList[i]
        )
      }
    },
    selectUserClick() {
      setTimeout(() => {
        this.$refs.pRelSelect.openPicker()
      }, 0)
    },
    changep(values) {
      this.saveForm()
    },
  },
}
</script>

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

.btnselect {
  position: relative;
  top: 2px;
  right: 80px;
  float: right;
  .batchselect {
    z-index: 100;
    margin-left: 10px;
  }
}
.btnselectmaintain {
  position: relative;
  float: right;
  .batchselect {
    z-index: 100;
    margin-right: -10px;
    margin-left: 10px;
  }
}
.maintaintable {
  :global(.ant-table-thead > tr > th) {
    border-right: none;
  }
  :global(.ant-table-bordered.ant-table-empty .ant-table-placeholder) {
    border: none;
  }
  :global(.ant-table-body table) {
    //  border-left:none;
    border: none;
  }
}
.exportClickBtn {
  color: #1890ff;
  cursor: pointer;
}
.upload {
  display: flex;
  .upload-list {
    width: calc(30% - 10px);
    margin-left: 10px;
    li {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 30px;
      padding: 0 10px;
      margin-bottom: 10px;
      line-height: 30px;
      border-radius: 4px;
      span {
        display: inline-block;
        width: 80%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
  .upload-data {
    width: 70%;
  }
}
</style>
