<template>
  <div class="component-search-table">
    <div class="component-search-table-container">
      <div class="component-search-table-nav-title">协议管理</div>
      <div class="component-search-table-form">
        <el-form ref="formRef" :model="formData" :rules="RULES" label-position="left" size="small">
          <el-row :gutter="12">
            <el-col :span="isTablet ? 12 : 6">
              <el-form-item label="组织" label-width="56px" prop="orgId">
                <Organ v-model="formData.orgId" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="component-search-table-btn-wrap">
                <el-button :loading="loading" type="primary" icon="el-icon-search" class="component-search-table-button" @click="handleSubmit">查询</el-button>
                <el-button class="component-search-table-button clear" @click="handleReset"><i class="component-search-table-icon-clear" />清除</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="component-search-table-table">
        <UploadAgreement ref="peopleAgreementRef" title="个人入网协议" v-model="peopleAgreement" :template-url="downloadUrls.peopleMouldUrl" :preview="preview" />
      </div>
      <div class="component-search-table-table">
        <UploadAgreement ref="companyAgreementRef" title="企业入网协议" v-model="companyAgreement" :template-url="downloadUrls.companyMouldUrl" :preview="preview" />
      </div>
      <div class="component-search-table-table">
        <UploadAgreement ref="realnameNoticeRef" title="实名制责任告知书" v-model="realnameNotice" :template-url="downloadUrls.realnameMouldUrl" :preview="preview" />
      </div>
      <div class="component-search-table-table">
        <UploadAgreement ref="companyAuthorizeRef" title="企业授权书" v-model="companyAuthorize" :show-vertical="false" :show-horizontal="false" :template-url="downloadUrls.authorizeMouldUrl" :preview="preview" />
      </div>
      <div class="component-search-table-table">
        <UploadAgreement ref="otherRef" title="个人授权书" v-model="other" :show-vertical="false" :show-horizontal="false" :template-url="downloadUrls.otherMouldUrl" :preview="preview" />
      </div>
      <div class="component-search-table-table">
        <UploadAgreement ref="logoRef" title="公司LOGO" v-model="logo" :show-word="false" :is-logo="true" :preview="preview" />
      </div>
    </div>
    <div class="btn-wrapper">
      <el-button v-if="preview" :loading="previewLoading" :disabled="!formData.orgId" type="primary" @click="handleClosePreview">编辑</el-button>
      <template v-else>
        <el-button @click="preview = true">取消</el-button>
        <el-button type="primary" @click="handleConfirmSelect" :loading="submitLoading">提交</el-button>
      </template>
    </div>
  </div>
</template>

<script>
import Organ from '@/components/Organ'
import UploadAgreement from './components/UploadAgreement'
import { queryPotocolManage, queryFileMould, updatePotocolManage, createPotocolManage } from '@/api/management'
import '@/components/SearchTable/index.scss'

const RULES = {
  orgId: {
    required: true,
    message: '请选择组织',
    trigger: 'change'
  }
}

/**
 * 创建协议文件对象
 */
function createAgreementFile(word = {}, vertical = {}, horizontal = {}) {
  return {
    word: { uuid: word.uuid, url: word.fileUrl ? require('@/assets/components/upload/ico_word_active.png') : '', fileUrl: word.fileUrl, name: word.fileName },
    horizontal: { uuid: horizontal.uuid, url: horizontal.fileUrl, fileUrl: horizontal.fileUrl, name: horizontal.fileName },
    vertical: { uuid: vertical.uuid, url: vertical.fileUrl, fileUrl: vertical.fileUrl, name: vertical.fileName }
  }
}

/**
 * 格式化成接口请求需要的数据
 * @param data 当前需要处理的对象
 * @param key  需要处理的字段
 */
function formatParams(data, key) {
  // 取出word和图片资源
  const { word, horizontal, vertical } = data
  return {
    [`${key}Word`]: word.uuid || '',
    [`${key}Horizontal`]: horizontal.uuid || '',
    [`${key}Vertical`]: vertical.uuid || ''
  }
}

export default {
  name: 'AgreementManage',
  components: { Organ, UploadAgreement },
  data() {
    // 组织id
    const { organId } = this.$store.getters
    return {
      loading: false,
      submitLoading: false,
      isSearched: false,
      formData: {
        orgId: organId
      },
      RULES,
      // logo
      logo: {
        horizontal: '',
        vertical: ''
      },
      // 是否请求过接口
      isFetched: false,
      // 下载的文件
      downloadUrls: {},
      // 编辑按钮的loading状态
      previewLoading: false,
      preview: true,
      peopleAgreement: createAgreementFile(),
      companyAgreement: createAgreementFile(),
      realnameNotice: createAgreementFile(),
      companyAuthorize: createAgreementFile(),
      other: createAgreementFile(),
      isTablet: window.OS.isTablet
    }
  },
  mounted() {
    this.handleSubmit()
    this.fetchAgreementDownloadUrl()
  },
  methods: {
    /**
     * 提交方法
     * @param formData 提交的表单数据
     */
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
      } catch (error) {
        return
      }
      // 呈现loading状态
      this.loading = true
      try {
        // 获取接口返回值
        const respData = await queryPotocolManage(this.formData) || {}
        // 获取当前记录id
        this.formData.uuid = respData.uuid
        // 个人入网合同
        this.peopleAgreement = createAgreementFile(
          respData.peopleAgreementWord,
          respData.peopleAgreementVertical,
          respData.peopleAgreementHorizontal
        )
        // 企业入网合同
        this.companyAgreement = createAgreementFile(
          respData.companyAgreementWord,
          respData.companyAgreementVertical,
          respData.companyAgreementHorizontal
        )
        // 责任告知书
        this.realnameNotice = createAgreementFile(
          respData.realnameNoticeWord,
          respData.realnameNoticeVertical,
          respData.realnameNoticeHorizontal
        )
        // 企业授权书
        this.companyAuthorize = createAgreementFile(
          respData.companyAuthorizeWord
        )
        // 个人授权书
        this.other = createAgreementFile(
          respData.otherWord
        )
        // logo
        this.logo = createAgreementFile(
          {},
          respData.logoPc,
          respData.logoH5
        )
      } catch (error) {
        console.error(error)
      }
      // 打开预览状态
      this.preview = true
      // 关闭loading状态
      this.loading = false
    },

    /**
     * 关闭预览模式
     */
    async handleClosePreview() {
      // 展示loading框
      this.previewLoading = true
      try {
        // 加载一遍接口
        await this.handleSubmit()
        // 关闭预览模式
        this.preview = false
      } catch (error) {
        console.error(error)
      }
      // 编辑按钮不展示loading框
      this.previewLoading = false
    },

    /**
     * 获取下载地址
     */
    async fetchAgreementDownloadUrl() {
      // 获取当前下载路径
      this.downloadUrls = await queryFileMould(this.formData) || {}
    },

    /**
     * 确认用户上传的文件
     */
    async handleConfirmSelect() {
      try {
        // 先校验是否都输入完成
        await Promise.all([
          this.$refs.peopleAgreementRef.validate(),
          this.$refs.companyAgreementRef.validate(),
          this.$refs.realnameNoticeRef.validate(),
          this.$refs.companyAuthorizeRef.validate(),
          this.$refs.logoRef.validate(),
          this.$refs.otherRef.validate()
        ])
      } catch (error) {
        return
      }
      // 提交按钮呈现loading状态
      this.submitLoading = true
      try {
        // 请求方法
        const requestFn = this.formData.uuid ? updatePotocolManage : createPotocolManage
        // 开始创建协议
        await requestFn({
          ...this.formData,
          ...formatParams(this.peopleAgreement, 'peopleAgreement'),
          ...formatParams(this.companyAgreement, 'companyAgreement'),
          ...formatParams(this.realnameNotice, 'realnameNotice'),
          ...formatParams(this.companyAuthorize, 'companyAuthorize'),
          ...formatParams(this.other, 'other'),
          logoPc: this.logo.vertical.uuid,
          logoH5: this.logo.horizontal.uuid
        })
        // 给出提示信息
        this.$message.success(`${this.formData.uuid ? '修改' : '提交'}成功`)
        // 重新请求一次接口
        this.handleSubmit()
      } catch (error) {
        console.error('提交报错：', error)
      }
      // 提交按钮管理loading状态
      this.submitLoading = false
    },

    /**
     * 重置
     */
    handleReset() {
      this.formData.orgId = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.component-search-table {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding-bottom: 0px;
  .component-search-table-container {
    flex: 1;
    overflow: auto;
    padding-bottom: 12px;
  }
  .btn-wrapper {
    align-items: center;
    background: #FFFFFF;
    box-shadow: 0px 0px 12px 0px rgba(196, 198, 207, 0.21);
    border-radius: 0px 0px 0px 8px;
    display: flex;
    height: 64px;
    justify-content: center;
  }
}
</style>
