<template>
  <sd-webflow
    ref="docform"
    :key="key"
    :validate-form="validForm"
    :removed-tabs="['sdRelatedDoc']"
    @actionBtnClick="actionBtnClick"
  >
    <template v-slot:form="{ model, fields, FlowData }">
      <!-- 初始化模型基础信息 -->
      <table v-if="isInitData || initData(model, fields, FlowData)">
        <tr>
          <td colspan="4" style="border:none">
            <audit-advanced-group
              :expand="auditBaseGroup"
              :expand-str="'auditBaseGroup'"
              :group-label="'风险审计信息'"
              @changedClick="changedClick"
            />
          </td>
        </tr>
        <template v-if="auditBaseGroup">
          <tr v-for="(item, i) in baseFormData" :key="i">
            <sd-form-item-td
              v-for="(child, j) in item"
              :key="j"
              :name="child.key"
              :label="child.name"
              :input-props="{ disabled: true }"
            />
          </tr>
        </template>
      </table>

      <div v-if="auditBaseGroup" :class="$style.onlydiv">
        <!--todo 模型逻辑 -->
        <p :class="$style.modelIdea">模型逻辑:</p>
        <SdQuillEditor v-model="model.configIdea" :options="editorOption" />
      </div>

      <!-- 线索信息 -->
      <table>
        <tr>
          <td colspan="4" style="border:none">
            <audit-advanced-group
              :expand="auidtInfoGroup"
              :expand-str="'auidtInfoGroup'"
              :group-label="'审计线索信息'"
              @changedClick="changedClick"
            />
          </td>
        </tr>
      </table>

      <div v-if="auidtInfoGroup" :class="$style.onlydiv">
        <AuditRiskDetail :search-data="infoSearchData" search-type="component"></AuditRiskDetail>
      </div>

      <!-- 整改人能看到的模块 -->
      <template v-if="isViewType === 0">
        <!-- 判定问题 -->
        <table>
          <tr>
            <td colspan="4" style="border:none">
              <audit-advanced-group
                :expand="auditJudgeGroup"
                :expand-str="'auditJudgeGroup'"
                :group-label="'判定问题'"
                @changedClick="changedClick"
              />
            </td>
          </tr>
          <template v-if="auditJudgeGroup">
            <tr>
              <sd-form-item-td :name="'questionFlag'" :label="'是否为问题'">
                <a-select v-model="questionFormData.questionFlag" placeholder="请选择问题判定">
                  <a-select-option :value="1">是</a-select-option>
                  <a-select-option :value="0">否</a-select-option>
                </a-select>
              </sd-form-item-td>
              <sd-form-item-td
                v-if="questionFormData.questionFlag === 0"
                :name="'problemStatementId'"
                :label="'非问题标签'"
              >
                <a-select
                  v-model="questionFormData.problemStatementId"
                  placeholder="请选择非问题标签"
                >
                  <a-select-option
                    v-for="(item, index) in nonQuestionList"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </sd-form-item-td>
            </tr>
            <tr v-if="questionFormData.questionFlag === 0">
              <sd-form-item-td>
                <a-input
                  v-model="questionFormData.nonQuestionDesc"
                  placeholder="请填写非问题说明"
                  :auto-size="{ minRows: 5, maxRows: 5 }"
                  type="textarea"
                  :disabled="true"
                />
              </sd-form-item-td>
            </tr>
          </template>
        </table>

        <!-- 说明 -->
        <table>
          <tr>
            <td colspan="4" style="border:none">
              <audit-advanced-group
                :expand="auditDescGroup"
                :expand-str="'auditDescGroup'"
                :group-label="'说明'"
                @changedClick="changedClick"
              />
            </td>
          </tr>
          <template v-if="auditDescGroup">
            <tr>
              <sd-form-item-td>
                <a-input
                  v-model="model.reformDesc"
                  placeholder="请填写整改说明"
                  :auto-size="{ minRows: 5, maxRows: 5 }"
                  type="textarea"
                  :disabled="isViewType"
                />
              </sd-form-item-td>
            </tr>
          </template>
        </table>

        <!-- 附件 -->
        <table>
          <tr>
            <td colspan="4" style="border:none">
              <audit-advanced-group
                :expand="auditAttachmentGroup"
                :expand-str="'auditAttachmentGroup'"
                :group-label="'附件'"
                @changedClick="changedClick"
              />
            </td>
          </tr>
        </table>

        <template v-if="auditAttachmentGroup">
          <div :class="$style.onlydiv">
            <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>
          </div>
        </template>
      </template>
      <template v-else>
        <!--审计线索明细  -->
        <table>
          <tr>
            <td colspan="4" style="border:none">
              <audit-advanced-group
                :expand="auditXsGroup"
                :expand-str="'auditXsGroup'"
                :group-label="'审计线索明细'"
                @changedClick="changedClick"
              />
            </td>
          </tr>
          <template v-if="auditXsGroup">
            <tr>
              <sd-form-item-td :name="'viewAccount'" :label="'整改人'"> </sd-form-item-td>
              <sd-form-item-td :name="'reviewer'" :label="'初审人'"> </sd-form-item-td>
            </tr>
            <!-- 非问题标签 非问题说明， 说明 附件 问题性质 -->
            <tr>
              <sd-form-item-td :name="'nonQuestionDesc'" :label="'非问题说明'">
                <a-input
                  v-model="model.nonQuestionDesc"
                  :auto-size="{ minRows: 5, maxRows: 5 }"
                  type="textarea"
                  :disabled="true"
                />
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td :name="'reformDesc'" :label="'说明'">
                <a-input
                  v-model="model.reformDesc"
                  :auto-size="{ minRows: 5, maxRows: 5 }"
                  type="textarea"
                  :disabled="true"
                />
              </sd-form-item-td>
            </tr>
            <!-- 附件 -->
            <tr>
              <sd-form-item-td :name="'attachment'" :label="'附件'">
                <p
                  v-for="(item, i) in model.attachment.split(',')"
                  :key="i"
                  @click="exportClick(record, i)"
                  >{{ item }}</p
                >
              </sd-form-item-td>
            </tr>
            <!-- 问题性质 -->
            <tr v-if="isViewType === 1">
              <sd-form-item-td :name="'questionNature'" :label="'问题性质'">
                <a-select v-model="model.questionNature" placeholder="请选择问题性质">
                  <a-select-option v-for="(item, i) in questionOption" :key="i" :value="item">{{
                    item
                  }}</a-select-option>
                </a-select>
              </sd-form-item-td>
            </tr>
            <tr v-else>
              <!-- 只读问题性质 -->
              <sd-form-item-td
                :name="'questionNature'"
                :label="'问题性质'"
                :input-props="{ disabled: true }"
              />
            </tr>
          </template>
        </table>
      </template>
    </template>
  </sd-webflow>
</template>

<script>
import components from './_import-components/audit-issued-form-import'
import { message } from 'ant-design-vue'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import AuditRiskDetail from './audit-risk-detail.vue'
import download from '@/common/services/download'
import { sdLocalStorage } from '@/common/services/storage-service'
import axios from '@/common/services/axios-instance'
import SdQuillEditor from '@/common/components/sd-quill-editor.vue'
import { getUserInfo } from '@/common/store-mixin'
import moment from 'moment'
const xzList = [
  '有业务无制度',
  '有制度难执行',
  '制度太宽泛缺乏操作细则',
  '制度过时不具备可操作性',
  '制度脱离实际难落地实施',
  '有制度未遵循',
  '特殊事项已经线下审批',
  '事项紧急重目标轻合规',
  '制度理解存在人为偏差',
  '工作疏忽未按制度行事',
  '人为规避制度管控要求',
]
const baseData = [
  [
    {
      name: '业务编码',
      key: 'businessCode',
    },
    {
      name: '模型编码',
      key: 'modelCode',
    },
  ],
  [
    {
      name: '模型类型',
      key: 'modelType',
    },
    {
      name: '模型名称',
      key: 'modelName',
    },
  ],
  [
    // todo 字段需要确认
    {
      name: '业务领域',
      key: 'businessDomain',
    },
    {
      name: '业务阶段',
      key: 'businessStage',
    },
  ],
  [
    {
      name: '单位',
      key: 'unit',
    },
    {
      name: '二级单位',
      key: 'secondUnit',
    },
  ],
  [
    {
      name: '问题推送时间',
      key: 'pushDate',
    },
    {
      name: '整改截至日期',
      key: 'reformDeadline',
    },
  ],
  [
    {
      name: '关注风险',
      key: 'risk',
    },
  ],
  [
    {
      name: '整改说明',
      key: 'reformDesc',
    },
  ],
]
export default {
  name: 'AuditIssuedForm',
  metaInfo: {
    title: 'AuditIssuedForm',
  },
  components: {
    auditAdvancedGroup,
    AuditRiskDetail,
    SdQuillEditor,
    ...components,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      // 流程 key
      key: 0,
      // 控制流程模块展开
      auditBaseGroup: false,
      // 审计线索信息
      auidtInfoGroup: false,
      // 判定问题
      auditJudgeGroup: false,
      // 说明
      auditDescGroup: false,
      // 附件
      auditAttachmentGroup: false,
      // 审计线索明细
      auditXsGroup: false,
      baseFormData: baseData,
      // 问题性质
      questionOption: xzList,
      infoSearchData: {},
      // 是否是整改人
      isViewType: 0,
      // 问题判定
      questionFormData: {
        questionFlag: null,
        nonQuestionDesc: null,
        problemStatementId: null,
      },
      nonQuestionList: [],
      // 初始化 上传附件部分
      flagIs: true,
      fileList: [],
      fileListTemp: [],
      attachments: [],
      editorOption: {
        // 只读
        readOnly: true,
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // toggled buttons
              ['blockquote', 'code-block'],
              [{ header: 1 }, { header: 2 }], // custom button values
              [{ list: 'ordered' }, { list: 'bullet' }],
              [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
              [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
              [{ direction: 'rtl' }], // text direction
              [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ color: [] }, { background: [] }], // dropdown with defaults from theme
              [{ font: [] }],
              [{ align: [] }],
              ['clean'], // remove formatting button
              ['link', 'image'], // link and image, video
            ],
          },
        },
      },
      // 表单数据
      isInitData: false,
      webFlowData: {},
    }
  },
  computed: {
    actualAccept() {
      // 优先使用前端配置的类型限制，如未配置，则使用后端支持的类型
      return (
        this.accept || JSON.parse(sdLocalStorage.getItem('commonConfig') || '{}').attachType || ''
      )
    },
  },
  watch: {
    fileList: {
      handler(val) {
        this.fileListTemp = val.map((item) => {
          return {
            name: item.name,
            url: item.url,
          }
        })
      },
      immediate: true,
    },
    isInitData: {
      handler: function(val) {
        this.$nextTick(() => {
          this.setInitData()
        })
      },
    },
  },
  methods: {
    // 表单验证
    validForm(e) {
      return Promise.resolve(true)
    },
    actionBtnClick(evt, { button, FlowData }) {
      if (button.buttonId === 'G_1_FXWTSJ.4') {
        // todo问题性质选择
        // if (
        //   !this.classdata[0]?.questionNature &&
        //   this.isViewType &&
        //   !this.classdata[0]?.nonQuestionDesc
        // ) {
        //   evt.preventDefault()
        //   return Modal.warning({
        //     title: '提示',
        //     content: '请选择需要问题性质!',
        //   })
        // }
      }
      // 如果是处于第一阶段则需要选择问题性质
      if (this.isViewType) {
        // 判断问题性质是否已经选择
        if (!this.model.questionNature) {
          evt.preventDefault()
          message.warning('请选择问题性质')
        }
      }
      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()
            })
          })
        )
      }
    },
    saveForm() {
      return new Promise((resolve) => {
        // 如果没有则提示请选择问题类型
        if (this.questionFormData.questionFlag !== 0 || this.questionFormData.questionFlag !== 1) {
          message.warning('请选择问题类型')
          resolve(false)
        }
        // 校验非问题类型参数
        if (this.questionFormData.questionFlag === 0) {
          if (!this.questionFormData.problemStatementId) {
            message.warning('请选择非问题标签')
            resolve(false)
          }
          if (!this.questionFormData.nonQuestionDesc) {
            message.warning('请填写非问题说明')
            resolve(false)
          }
        }
        // 校验说明是否有值
        if (!this.model.reformDesc) {
          message.warning('请填写整改说明')
          resolve(false)
        }

        // 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.initType) {
        //     // 没有初审人，设置初审人
        //     if (!this.classdata[0].checker) {
        //       this.$refs.docform.setFieldValue('checker', account)
        //       this.$refs.docform.setFieldValue('checkDate', strTime)
        //     }
        //     // 有初审人并且没有终审人
        //     if (this.classdata[0].checker && !this.classdata[0].reviewer) {
        //       this.$refs.docform.setFieldValue('reviewer', account)
        //       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)
      })
    },
    // 初始化基础信息
    initData(model, fields, FlowData) {
      this.isInitData = true
      this.webFlowData = {
        model,
        fields,
        FlowData,
      }
      return true
    },
    setInitData() {
      const { model, fields, FlowData } = this.webFlowData
      // 获取来自路由的信息
      // 是否存在extParams
      if (this.$route.query.extParams) {
        const extParams = JSON.parse(this.$route.query.extParams) || []
        console.log('🚀 ~ initData ~ extParams:', extParams)
        Object.keys(extParams).forEach((val) => {
          if (extParams[val] === 'null') extParams[val] = null
          this.$refs.docform.setFieldValue(val, extParams[val])
        })
      }
      // 如果整改人是自己则可以上传
      // 显示信息
      // todo修改流程后更改
      const logInfo = FlowData.processLogInfo?.length || 0
      if (logInfo > 1) {
        this.isViewType = logInfo - 1
      }
      const account = getUserInfo().name
      const strTime = moment().format('YYYY-MM-DD')
      if (logInfo === 1) {
        // 给初审人赋值
        this.$refs.docform.setFieldValue('checker', account)
        this.$refs.docform.setFieldValue('checkDate', strTime)
      } else if (logInfo === 2) {
        this.$refs.docform.setFieldValue('reviewer', account)
        this.$refs.docform.setFieldValue('reviewDate', strTime)
        // 给终审人赋值
      } else {
        this.$refs.docform.setFieldValue('viewAccount', account)
        this.$refs.docform.setFieldValue('reformDate', strTime)
        this.$refs.docform.setFieldValue('title', getUserInfo().name + '风险审核')
        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
        }
      }
      // 初始化线索信息
      this.infoSearchData = {
        // modelCode: model.modelCode,
        // businessCode: model.businessCode,
      }
      this.auditBaseGroup = true
      this.auidtInfoGroup = true
      this.auditJudgeGroup = true
      this.auditDescGroup = true
      this.auditAttachmentGroup = true
      this.auditXsGroup = true
    },

    // 非问题处理
    // 附件上传
    // 附件自定义上传
    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)
    },
    // 下载附件
    exportClick(row, i) {
      const attachmentList = row.attachment.split(',')
      const fileNameList = row.fileName.split(',')
      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]
      )
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.upload {
  display: flex;
  min-width: 800px;
  min-height: 200px;
  .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%;
  }
}
.model-idea {
  // 上下边距
  margin: 10px 0;
}
.onlydiv {
  width: 90%;
  margin: 0 auto;
}
</style>
