<template>
  <div class="enterprise-management">
    <router-view />
    <template v-if="!$route.params.id">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleTabClick">
        <el-tab-pane v-if="btnPermission.includes('tradingPlatform')" label="贸易平台" name="pending"></el-tab-pane>
        <el-tab-pane v-if="btnPermission.includes('electronicSign')" label="电子签" name="all"></el-tab-pane>
        <div>
          <div class="search">
            <div class="left">
              <el-button v-if="activeName === 'pending' && btnPermission.includes('addSupplier')" type="primary" style="margin-bottom: 15px" @click="() => { this.$refs.tradePlatform.show = true }">新增贸易平台</el-button>
              <!-- <el-button v-if="activeName === 'pending'" type="primary" style="margin-bottom: 15px" @click="() => { this.$refs.tradePlatform.show = true }">新增贸易平台</el-button> -->
              <div v-if="activeName == 'all'" class="left" style="margin-bottom: 15px;">
                <el-radio-group v-model="tableType" class="other-radio" @change="changeSignType">
                  <el-radio-button label="com">公司</el-radio-button>
                  <el-radio-button label="person">个人</el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <div class="right">
              <template v-if="activeName === 'all'">
                <div style="margin-bottom: -5px;">
                  <el-select
                    v-model="search.status"
                    placeholder="请选择认证状态"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in statusList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </div>
                <div style="margin-bottom: -5px;">
                  <el-input
                    v-model="search.name"
                    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>
                </div>
              </template>
            </div>
          </div>
          <cy-comm-table
            v-show="!loading"
            ref="commTable"
            :loading="loading"
            :columns="getColumns"
            :table-options="tableOptions"
            :data="tableData"
            :count="total"
            parent-component="EnterpriseManagement"
          />
        </div>
      </el-tabs>
      <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>
        <template slot="footer">
          <el-button type="normal" @click="$refs.comDetail.show = false">关闭</el-button>
        </template>
      </cy-dialog>
      <cy-dialog ref="personDetail" title="个人信息">
        <el-form
          ref="personDetailForm"
          v-loading="isLoading"
          :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="证照正面：" prop="enterpriseCardPhotoIds">
            <cy-upload
              ref="fileStorage"
              :upload-params="{ mouldName: 'enterpriseCardPhoto' }"
              :file-data="personDetailForm.enterpriseCardPhotoList"
              :upload-from-orange-status="true"
              placeholder="请上传附件"
              :is-call-back="true"
              :limit="1"
              :disabled="personDetailIsView"
              @upload="setAddId($event, 1)"
              @remove="setDeleteId($event, 1)"
            />
          </el-form-item>
          <el-form-item label="证照反面：" prop="enterpriseCardRevPhotoIds">
            <cy-upload
              ref="fileStorage"
              :upload-params="{ mouldName: 'enterpriseCardRevPhoto' }"
              :file-data="personDetailForm.enterpriseCardRevPhotoList"
              :upload-from-orange-status="true"
              :is-call-back="true"
              placeholder="请上传附件"
              :limit="1"
              :disabled="personDetailIsView"
              @upload="setAddId($event, 2)"
              @remove="setDeleteId($event, 2)"
            />
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button type="primary" @click="confirmPerson">确定</el-button>
          <el-button type="normal" @click="$refs.personDetail.show = false">关闭</el-button>
        </template>
      </cy-dialog>
      <cy-dialog ref="tradePlatform" title="添加平台">
        <div class="multiple-form">
          <div>
            <div class="required">输入关键字：</div>
            <div>
              <el-input v-model="ruleForm.keyWord" placeholder="请输入关键字">
                <el-button slot="append" icon="el-icon-search" :loading="searchLoading" @click="searchCompany"></el-button>
              </el-input>
            </div>
          </div>
          <div>
            <div class="required">企业名称：</div>
            <div>
              <el-select ref="company" v-model="ruleForm.wholeKeyWord" style="width: 100%" placeholder="请选择企业">
                <el-option
                  v-for="item in companyNameList"
                  :key="item.enterpriseName"
                  :label="item.enterpriseName"
                  :value="item.enterpriseName"
                >
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="submit-btn">
          <el-button @click="() => { this.$refs.tradePlatform.show = false }">关闭</el-button>
          <el-button type="primary" @click="tradePlatformAdd">确定</el-button>
        </div>
      </cy-dialog>
      <cy-dialog ref="certificationDetails" title="认证信息">
        <el-form
          ref="certificationRef"
          :model="certificationForm"
          :rules="rules"
          label-position="top"
          label-width="150px"
          class="rule-form-orange"
        >
          <el-form-item label="企业认证方式" style="width: 100%">
            <el-input
              v-model="certificationForm.verifyType"
              placeholder="请输入企业认证方式"
              readonly
            >
            </el-input>
          </el-form-item>
          <el-form-item label="姓名" style="width: 100%">
            <el-input
              v-model="certificationForm.legalName"
              placeholder="请输入姓名"
              readonly
            />
          </el-form-item>
          <el-form-item label="身份证号" style="width: 100%">
            <el-input
              v-model="certificationForm.legal"
              placeholder="请输入身份证号"
              readonly
            >
            </el-input>
          </el-form-item>
          <el-form-item label="手机号" style="width: 100%">
            <el-input
              v-model="certificationForm.legalMobile"
              placeholder="请输入手机号"
              readonly
            />
          </el-form-item>
        </el-form>
        <div class="submit-btn">
          <el-button @click="() => { this.$refs.certificationDetails.show = false }">关闭</el-button>
        </div>
      </cy-dialog>
    </template>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import indexTable from './indexTable'
import signComTable from './signComTable'
import signPersonTable from './signPersonTable'
import request from '@/utils/request'
import { refreshAuthLink, getCompanyNameFormKey, platformAdd, getAuthInfo, platformFlush } from '@/api/enterpriseManagement/enterpriseManagement'
export default {
  name: 'EnterpriseManagement',
  mixins: [indexTable, signComTable, signPersonTable],
  data() {
    this.statusList = [
      { name: '未认证', id: 0 },
      { name: '已认证', id: 1 }
    ]
    return {
      loading: false,
      activeName: 'pending',
      tableType: 'com',
      search: {
        name: '',
        status: ''
      },
      disabled: false,
      value: '',
      tradePage: 1,
      tradeSize: 10,
      comPage: 1,
      comSize: 10,
      comName: '',
      comStatus: '',
      personPage: 1,
      personSize: 10,
      personName: '',
      personStatus: '',
      comDetail: {
        legal: '',
        legalMobile: '',
        legalName: '',
        verifyType: ''
      },
      personDetailForm: {
        name: '',
        mobile: '',
        id: '',
        cardType: '',
        socialCreditCode: '',
        enterpriseCardPhotoList: [],
        enterpriseCardRevPhotoList: [],
        enterpriseCardPhotoIds: [],
        enterpriseCardRevPhotoIds: [],
        deleteIds: [],
        fileIds: []
      },
      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: '请选择证件类型' }],
        enterpriseCardPhotoIds: [{ required: true, trigger: 'change', message: '请上传证照正面' }],
        enterpriseCardRevPhotoIds: [{ required: true, trigger: 'change', message: '请上传证照反面' }]
      },
      isLoading: false,
      searchLoading: false,
      restaurants: [],
      ruleForm: {
        keyWord: '',
        wholeKeyWord: '',
        enterpriseCustomerInfoId: ''
      },
      companyNameList: [],
      certificationForm: {
        verifyType: '',
        legalName: '',
        legal: '',
        legalMobile: ''
      },
      rules: {},
      formKey: 0,
      btnPermission: JSON.parse(sessionStorage.getItem('buttons')) || [],
      personDetailIsView: false,
      typeList: []
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ]),
    getColumns() {
      const list = this.activeName === 'pending' ? this.columns : this.tableType === 'com' ? this.comSigncolumns : this.personSigncolumns
      return list
    }
  },
  created() {
    if (!this.btnPermission.includes('tradingPlatform')) {
      this.activeName = 'all'
    }
  },
  mounted() {
    this.fetchData()
    this.getTypeList()
  },
  methods: {
    getTypeList() {
      request({
        url: '/dictionary/do_findByParentCode',
        method: 'get',
        params: {
          parentCode: 'certificateType'
        }
      }).then(({ data }) => {
        this.typeList = data || []
      })
    },
    fetchData() {
      if (this.page === 1) {
        this.loading = true
      }
      const url = this.activeName === 'pending' ? '/platform/findPage' : this.tableType === 'com' ? '/electronic/signature/personal/findByComName' : '/electronic/signature/personal/findByName'
      const data = this.activeName === 'pending' ? {} : { name: this.search.name, status: this.search.status }
      request({
        url,
        method: 'get',
        params: {
          page: this.page,
          rows: this.size,
          ...data
        }
      }).then(({ rows, records }) => {
        this.tableData = rows || []
        this.total = records
        this.loading = false
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          return false
        }
      })
    },
    paymentAccountNameSearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handlerOperate(type, row) {
      switch (type) {
        case 'edit':
          this.$router.push({
            name: 'InvoiceInformation',
            params: { id: 'children' },
            query: {
              id: row.id
            }
          })
          break
        case 'comUrlDetail':
          this.getComDetail(row.socialCreditCode)
          break
        case 'createComUrl':
          this.createUrl(row.id, 'com')
          break
        case 'createPersonUrl':
          this.createUrl(row.id, 'person')
          break
        case 'refreshTable':
          this.fetchData()
          break
        case 'comUrlDelete':
          this.deleteUrl(row.id, 'com')
          break
        case 'personUrlDelete':
          this.deleteUrl(row.id, 'person')
          break
        case 'updatePersonUrl':
          this.getPersonDetail(row.id, 'update')
          break
        case 'copyUrl':
          this.copyUrl(row.shortAuthUrl)
          break
        case 'copyAutoUrl':
          this.copyUrl(row.shortAutoSignUrl)
          break
        case 'automaticSigning':
          this.automaticSigning(row.shortAutoSignUrl)
          break
        case 'refreshAuthLink':
          this.refreshAuthLink(row.id)
          break
        case 'refreshStatus':
          this.platformFlush(row.id)
          break
        case 'see':
          this.certificationDetails(row.socialCreditCode)
          break
        case 'refreshComUrl':
          // this.fetchData()
          this.refreshSignStatus(row.fddCustomerId, 'com')
          break
        case 'refreshPersonUrl':
          // this.fetchData()
          this.refreshSignStatus(row.id, 'person')
          break
        case 'personUrlDetail':
          this.getPersonDetail(row.id, 'view')
          break
      }
    },
    handleTabClick(tab) {
      if (tab.name === 'all') {
        this.tableType = 'com'
      }
      // this.setListParams(tab.name, tab.name == 'pending' ? this.tableType : null, null)
      this.page = this.$refs.commTable.page = 1
      this.size = this.$refs.commTable.size = 10
      this.search.name = ''
      this.search.status = ''
      this.fetchData()
    },
    changeSignType(val) {
      // this.setListParams(this.activeName, val == 'com' ? 'person' : 'com', val)
      this.page = 1
      this.size = 10
      this.search.name = ''
      this.search.status = ''
      this.fetchData()
    },
    setListParams(newActiveName, oldSignType, newSignType) {
      if (newActiveName === 'pending' || oldSignType) {
        this[`${oldSignType}Page`] = this.page
        this[`${oldSignType}Size`] = this.size
        this[`${oldSignType}Name`] = this.search.name
        this[`${oldSignType}Status`] = this.search.status
      } else {
        this.tradePage = this.page
        this.tradeSize = this.size
      }
      this.page = this.$refs.commTable.page = newActiveName === 'pending' ? this.tradePage : !oldSignType ? this.comPage : this[`${newSignType}Page`]
      this.size = this.$refs.commTable.size = newActiveName === 'pending' ? this.tradeSize : !oldSignType ? this.comSize : this[`${newSignType}Size`]
      if (newActiveName === 'all') {
        this.search.name = !oldSignType ? this.comName : this[`${newSignType}Name`]
        this.search.status = !oldSignType ? this.comStatus : this[`${newSignType}Status`]
      }
      this.fetchData()
    },
    getComDetail(fddCustomerId) {
      // const data = new FormData()
      // data.append('fddCustomerId', fddCustomerId)
      request({
        url: '/purchContract/confirm/getAuthInfo',
        method: 'post',
        data: {
          fddCustomerId
        }
      }).then(({ data }) => {
        this.comDetail = { ...data }
        this.$refs.comDetail.show = true
      })
    },
    createUrl(id, type) {
      // this.$confirm('确认重新生成认证链接吗？', '重新生成认证链接', {
      //   cancelButtonText: '取消',
      //   confirmButtonText: '确定',
      //   type: 'warning'
      // }).then(() => {
      const url = type === 'com' ? '/customer/flushUrlByCompany' : '/electronic/signature/personal/flushUrl'
      request({
        url,
        method: 'get',
        params: { id }
      }).then(() => {
        this.$message.success('刷新成功')
        this.fetchData()
      })
      // })
    },
    deleteUrl(id, type) {
      this.$confirm('确认删除吗？', '删除', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        const url = type === 'com' ? '/customer/deleteCustomer' : '/electronic/signature/personal/delete'
        request({
          url,
          method: 'post',
          params: { id }
        }).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        })
      })
    },
    getPersonDetail(id, type) {
      request({
        url: '/electronic/signature/personal/get',
        method: 'get',
        params: { id }
      }).then(({ data }) => {
        this.personDetailForm.name = data.name
        this.personDetailForm.mobile = data.mobile
        this.personDetailForm.cardType = data.cardType
        this.personDetailForm.socialCreditCode = data.socialCreditCode
        this.personDetailForm.enterpriseCardPhotoList = data.cardPhotoFile ? [data.cardPhotoFile] : []
        this.personDetailForm.enterpriseCardRevPhotoList = data.cardRevPhotoFile ? [data.cardRevPhotoFile] : []
        this.personDetailForm.enterpriseCardPhotoIds = data.cardPhotoFile ? [data.cardPhotoFile.id] : []
        this.personDetailForm.enterpriseCardRevPhotoIds = data.cardRevPhotoFile ? [data.cardRevPhotoFile.id] : []
        this.personDetailForm.id = data.id
        this.$refs.personDetail.show = true
        this.personDetailIsView = type === 'view'
      })
    },
    submitPersonInfo() {
      this.isLoading = true
      const data = new FormData()
      data.append('name', this.personDetailForm.name)
      data.append('mobile', this.personDetailForm.mobile)
      data.append('id', this.personDetailForm.id)
      data.append('cardType', this.personDetailForm.cardType)
      data.append('socialCreditCode', this.personDetailForm.socialCreditCode)
      data.append('fileIds[0]', this.personDetailForm.enterpriseCardPhotoIds[0])
      data.append('fileIds[1]', this.personDetailForm.enterpriseCardRevPhotoIds[0])
      if (this.personDetailForm.deleteIds.length) {
        this.personDetailForm.deleteIds.forEach((item, index) => {
          data.append(`deleteIds[${index}]`, item)
        })
      }
      request({
        url: '/electronic/signature/personal/update',
        method: 'post',
        data
      }).then(() => {
        this.isLoading = false
        this.$refs.personDetail.show = false
        this.fetchData()
      }, () => {
        this.isLoading = false
      })
    },
    confirmPerson() {
      this.$refs.personDetailForm.validate(flag => {
        if (flag) {
          this.submitPersonInfo()
        } else {
          this.$message.error('必填项不能为空')
        }
      })
    },
    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)
    },
    automaticSigning(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()
      })
    },
    platformFlush(id) {
      platformFlush({ id: id }).then(data => {
        this.fetchData()
        this.$message.success('刷新成功')
      })
    },
    searchCompany() {
      getCompanyNameFormKey({ condition: this.ruleForm.keyWord }).then(({ data }) => {
        this.companyNameList = data
        this.$refs['company'].toggleMenu()
      })
    },
    tradePlatformAdd() {
      const companyList = this.companyNameList.find(item => item.enterpriseName === this.ruleForm.wholeKeyWord)
      const params = {
        Loading: true,
        platformName: this.ruleForm.wholeKeyWord,
        socialCreditCode: companyList.socialCreditCode,
        phoneNumber: companyList.phoneNumber,
        address: companyList.address
      }
      platformAdd(params).then(() => {
        this.$message.success('添加成功')
        this.$refs.tradePlatform.show = false
        this.fetchData()
        // this.$router.push({ name: 'enterpriseManagement' })
      })
    },
    certificationDetails(socialCreditCode) {
      this.$refs.certificationDetails.show = true
      getAuthInfo({ fddCustomerId: socialCreditCode }).then(({ data }) => {
        this.certificationForm = data
      })
    },
    refreshSignStatus(id, type) {
      request({
        url: type === 'com' ? '/purchContract/confirm/getAuthStatus' : '/electronic/signature/personal/flush',
        method: 'get',
        params: type === 'com' ? { customerId: id } : { id }
      }).then(() => {
        this.$message.success('刷新成功')
        this.fetchData()
      })
    },
    setAddId(info, index) {
      if (index === 1) {
        this.personDetailForm.enterpriseCardPhotoIds.push(info[0].response.data[0].id)
      } else {
        this.personDetailForm.enterpriseCardRevPhotoIds.push(info[0].response.data[0].id)
      }
    },
    setDeleteId(info, index) {
      if (index === 1) {
        this.personDetailForm.deleteIds.push(this.personDetailForm.enterpriseCardPhotoIds[0])
        this.personDetailForm.enterpriseCardPhotoIds.splice(0, 1)
      } else {
        this.personDetailForm.deleteIds.push(this.personDetailForm.enterpriseCardRevPhotoIds[0])
        this.personDetailForm.enterpriseCardRevPhotoIds.splice(0, 1)
      }
    }
  }
}
</script>

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

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