<template>
  <div class="enterprise-management">
    <router-view />
    <template v-if="!$route.params.id">
      <div>
        <div class="search">
          <div class="left">
            <div class="left" style="margin-bottom: 15px;">
              <el-radio-group v-model="tableType" class="other-radio" @change="changeSignType">
                <el-radio-button v-power="'company'" label="com">公司</el-radio-button>
                <el-radio-button v-power="'individual'" label="person">个人</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="right">
            <div>
              <el-select
                v-model="search.status"
                placeholder="请选择认证状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in [
                    { name: '未认证', id: 0 },
                    { name: '已认证', id: 1 }
                  ]"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
            <div style="margin-bottom: -5px;">
              <el-input
                v-model="search.keyword"
                style="width: 300px"
                :placeholder="tableType == 'com' ? '请输入公司名称/统一社会信用代码' : '请输入姓名/证件号码'"
                clearable
              >
              </el-input>
            </div>
            <div class="leftBtn" style="margin-bottom: -5px;">
              <el-button type="primary" @click="fetchData">查询</el-button>
              <template v-if="tableType === 'person'">
                <el-button v-power="'individualAdd'" type="primary" @click="handlerOperate('addPerson', '')">新增</el-button>
              </template>

              <template v-if="tableType === 'com'">
                <el-button v-power="'companyAuthAddDetail'" type="primary" @click="handlerOperate('addCompany', '')">新增</el-button>
              </template>

            </div>
          </div>
        </div>
        <cy-comm-table
          ref="commTable"
          :loading="loading"
          :columns="getColumns"
          :table-options="{
            maxHeight: 'calc(100vh - 330px)',
            height: 'calc(100vh - 330px)'
          }"
          :data="tableData"
          :count="total"
          parent-component="EnterpriseManagement"
        />
      </div>
      <cy-dialog ref="comDetail" title="认证平台">
        <table border class="view-table" cellspacing="0" style="table-layout: fixed">
          <tr><th>企业认证方式：</th><td colspan="5">{{ comDetail.verifyType }}</td></tr>
          <tr><th>姓名：</th><td colspan="5">{{ comDetail.legalName }}</td></tr>
          <tr><th>身份证号：</th><td colspan="5">{{ comDetail.legal }}</td></tr>
          <tr><th>手机号：</th><td colspan="5">{{ comDetail.legalMobile }}</td></tr>
        </table>

        <div class="submit-btn">
          <el-button type="normal" @click="$refs.comDetail.show = false">关闭</el-button>
        </div>
      </cy-dialog>

      <cy-dialog ref="personDetail" title="个人信息">
        <el-form
          ref="personDetailForm"
          :model="personDetailForm"
          :rules="personDetailFormRules"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="姓名：" prop="name">
            <el-input
              v-model="personDetailForm.name"
              placeholder="请输入姓名"
              :disabled="personDetailIsView"
            ></el-input>
          </el-form-item>
          <el-form-item label="电话：" prop="mobile">
            <el-input
              v-model="personDetailForm.mobile"
              placeholder="请输入电话"
              :disabled="personDetailIsView"
            ></el-input>
          </el-form-item>
          <el-form-item label="证件类型：" prop="cardType">
            <el-select
              v-model="personDetailForm.cardType"
              :disabled="personDetailIsView"
              placeholder="请选择证件类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in typeList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="证件号码：" prop="socialCreditCode">
            <el-input
              v-model="personDetailForm.socialCreditCode"
              placeholder="请输入证件号码"
              :disabled="personDetailIsView"
            ></el-input>
          </el-form-item>
          <el-form-item label="证照正面：" class="form-required">
            <cy-upload
              ref="fileStoragePersonCard"
              :upload-params="{ fileType: 'enterpriseCardPhoto' }"
              :file-data="personDetailForm.enterpriseCardPhotoList"
              :upload-from-orange-status="true"
              placeholder="请上传附件"
              :is-call-back="true"
              :limit="1"
              :disabled="personDetailIsView"
            />
          </el-form-item>
          <el-form-item label="证照反面：" class="form-required">
            <cy-upload
              ref="fileStoragePersonCardRev"
              :upload-params="{ fileType: 'enterpriseCardRevPhoto' }"
              :file-data="personDetailForm.enterpriseCardRevPhotoList"
              :upload-from-orange-status="true"
              :is-call-back="true"
              placeholder="请上传附件"
              :limit="1"
              :disabled="personDetailIsView"
            />
          </el-form-item>
        </el-form>
        <div v-if="!personDetailIsView" class="submit-btn">
          <el-button @click="$refs.personDetail.show = false">关闭</el-button>
          <el-button type="primary" @click="confirmPerson">确定</el-button>
        </div>
      </cy-dialog>

      <cy-dialog ref="comInfoRef" title="公司信息">
        <el-form
          ref="comInfoForm"
          :model="comInfoForm"
          :rules="comInfoFormRules"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="公司名称" prop="name">
            <custom-select
              :value.sync="comInfoForm.name"
              :disabled="disabled"
              placeholder="请输入公司名称"
              @search-click="searchClick"
              @search-change="searchChange"
            >
              <el-option
                v-for="item in companyListData"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </custom-select>
          </el-form-item>
        </el-form>
        <div class="submit-btn">
          <el-button @click="$refs.comInfoRef.show = false">关闭</el-button>
          <el-button type="primary" @click="comInfoSubmit">确定</el-button>
        </div>
      </cy-dialog>
    </template>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import signComTable from './signComTable'
import signPersonTable from './signPersonTable'
import request from '@/utils/request'
import { refreshAuthLink, getESignPersonalList, getESignCompanyList, getESignPersonalDetails, addESignPersonal, updateESignPersonal, addCompany, getAuthInfo } from '@/api/enterpriseManage/eSign'
import { getEnterpriseInspectionInfo } from '@/api/dictionary'
export default {
  name: 'EnterpriseManagement',
  components: {
    CustomSelect: () => import('@/components/CustomSelect/index.vue')
  },
  mixins: [signComTable, signPersonTable],
  data() {
    return {
      loading: false,
      tableType: 'com',
      search: {
        keyword: '',
        status: ''
      },
      tableData: [],
      total: 0,
      disabled: false,
      comDetail: {
        legal: '',
        legalMobile: '',
        legalName: '',
        verifyType: ''
      },
      personDetailForm: {
        name: '',
        mobile: '',
        id: '',
        cardType: '',
        socialCreditCode: '',
        enterpriseCardPhotoList: [],
        enterpriseCardRevPhotoList: [],
        fileIds: []
      },
      deepPersonDetailForm: [],
      personDetailFormRules: {
        name: [{ required: true, trigger: 'blur', message: '请输入姓名' }],
        mobile: [{ required: true, trigger: 'blur', message: '请输入电话' }],
        socialCreditCode: [{ required: true, trigger: 'blur', message: '请输入证件号码' }],
        cardType: [{ required: true, trigger: 'change', message: '请选择证件类型' }]
      },
      certificationForm: {
        verifyType: '',
        legalName: '',
        legal: '',
        legalMobile: ''
      },
      btnPermission: JSON.parse(sessionStorage.getItem('buttons')) || [],
      personDetailIsView: false,
      typeList: [],
      companyListData: [],
      comInfoForm: {
        name: '',
        socialCreditCode: ''
      },
      comInfoFormRules: {
        name: [{ required: true, message: '请选择公司名称', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ]),
    getColumns() {
      const list = this.tableType === 'com' ? this.comSigncolumns : this.personSigncolumns
      return list
    }
  },

  created() {
    if (!this.btnPermission.includes('company')) {
      this.tableType = 'person'
    }
    this.deepPersonDetailForm = JSON.parse(JSON.stringify(this.personDetailForm))
    this.fetchData()
    this.getTypeList()
  },
  methods: {
    getTypeList() {
      request({
        url: '/dictionary/do_findByParentCode',
        method: 'get',
        params: {
          parentCode: 'certificateType'
        }
      }).then(({ data }) => {
        this.typeList = data || []
      })
    },

    changeSignType(val) {
      this.page = 1
      this.size = 10
      this.search.name = ''
      this.search.status = ''
      this.fetchData()
    },

    fetchData() {
      if (this.page === 1) {
        this.loading = true
      }
      const params = {
        page: this.page || 1,
        rows: this.size || 10,
        ...this.search
      }
      if (this.tableType === 'com') {
        getESignCompanyList(params).then(({ rows, records }) => {
          this.tableData = rows
          this.total = records
          this.loading = false
        })
      } else {
        getESignPersonalList(params).then(({ rows, records }) => {
          this.tableData = rows
          this.total = records
          this.loading = false
        })
      }
    },
    handlerOperate(type, row) {
      switch (type) {
        case 'addCompany':
          this.comInfoForm.name = ''
          this.$refs.comInfoRef.show = true
          break
        case 'comUrlDetail':
          this.getComDetail(row.id)
          break
        case 'createComUrl':
          this.createUrl(row.id, 'com')
          break
        case 'createPersonUrl':
          this.createUrl(row.id, 'person')
          break
        case 'copyUrl':
          this.copyUrl(row.shortAuthUrl)
          break
        case 'copyAutoUrl':
          this.copyUrl(row.shortAutoSignUrl)
          break
        case 'refreshAuthLink':
          this.refreshAuthLink(row.id)
          break
        case 'refreshComUrl':
          this.refreshSignStatus(row.id, 'com')
          break
        case 'refreshPersonUrl':
          this.refreshSignStatus(row.id, 'person')
          break
        case 'updatePersonUrl':
          this.getPersonDetail(row.id, 'update')
          break
        case 'personUrlDetail':
          this.getPersonDetail(row.id, 'view')
          break
        case 'addPerson':
          this.getPersonDetail('', 'add')
          break
      }
    },

    getComDetail(id) {
      getAuthInfo({ id }).then(({ data }) => {
        this.comDetail = data
        this.$refs.comDetail.show = true
      })
    },
    createUrl(id, type) {
      const url = type === 'com' ? '/electronic/signature/company/flushUrl' : '/electronic/signature/personal/flushUrl'
      request({
        url,
        method: 'get',
        params: { Loading: true, id }
      }).then(() => {
        this.$message.success('刷新成功')
        this.fetchData()
      })
    },

    getPersonDetail(id, type) {
      if (type !== 'add') {
        getESignPersonalDetails({ id }).then(({ data }) => {
          const { cardPhotoFile, cardRevPhotoFile } = data
          this.personDetailForm = {
            ...this.personDetailForm,
            ...data,
            enterpriseCardPhotoList: cardPhotoFile ? [cardPhotoFile] : [],
            enterpriseCardRevPhotoList: cardRevPhotoFile ? [cardRevPhotoFile] : []
          }
        })
      } else {
        this.personDetailForm = JSON.parse(JSON.stringify(this.deepPersonDetailForm))
      }
      this.$refs.personDetail.show = true
      this.personDetailIsView = type === 'view'
    },
    confirmPerson() {
      this.$refs.personDetailForm.validate(valid => {
        if (valid) {
          const { id } = this.personDetailForm
          const fileStoragePersonCard = this.$refs.fileStoragePersonCard.getFileLists.map(item => item.id)
          if (!fileStoragePersonCard.length) {
            this.$message.warning('请上传证照正面')
            return
          }
          const fileStoragePersonCardRev = this.$refs.fileStoragePersonCardRev.getFileLists.map(item => item.id)
          if (!fileStoragePersonCardRev.length) {
            this.$message.warning('请上传证照反面')
            return
          }
          const params = {
            Loading: true,
            ...this.personDetailForm,
            fileStoragePersonCard,
            fileIds: [...fileStoragePersonCard, ...fileStoragePersonCardRev]
          }
          if (id) {
            updateESignPersonal(params).then(() => {
              this.$refs.personDetail.show = false
              this.fetchData()
            })
          } else {
            addESignPersonal(params).then(() => {
              this.$refs.personDetail.show = false
              this.fetchData()
            })
          }
        } else {
          return false
        }
      })
    },

    copyUrl(url) {
      if (!url) {
        this.$message.error('尚未生成链接')
        return
      }
      const input = document.createElement('input')
      document.body.appendChild(input)
      input.setAttribute('value', url)
      input.select()
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        this.$message.success('复制成功')
      }
      document.body.removeChild(input)
    },

    refreshAuthLink(id) {
      refreshAuthLink({ id: id }).then(() => {
        this.$message.success('刷新成功')
        this.fetchData()
      })
    },

    refreshSignStatus(id, type) {
      request({
        url: type === 'com' ? '/electronic/signature/company/flushInfoFromSop' : '/electronic/signature/personal/flush',
        method: 'get',
        params: { Loading: true, id }
      }).then(() => {
        this.$message.success('刷新成功')
        this.fetchData()
      })
    },
    searchClick(val) {
      getEnterpriseInspectionInfo({ keyword: val }).then(({ data }) => {
        this.companyListData = data
      })
    },
    searchChange(val) {
      const obj = this.companyListData.find(item => item.name === val)
      if (!obj) return
      const { code } = obj
      this.comInfoForm = {
        ...this.comInfoForm,
        socialCreditCode: code
      }
    },
    comInfoSubmit() {
      this.$refs.comInfoForm.validate((valid) => {
        if (valid) {
          const params = {
            Loading: true,
            ...this.comInfoForm
          }
          addCompany(params).then(() => {
            this.$refs.comInfoRef.show = false
            this.$message.success('添加成功')
            this.fetchData()
            return
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.enterprise-management {

}
.other-radio .is-active .el-radio-button__inner {
  background-color: #E9423A;
  color: #ffffff;
  border-color: #E9423A;
  box-shadow: -1px 0 0 0 #E9423A;;
}
</style>
