<template>
  <div class="main-content">
    <EasyForm
      ref="inputDialog"
      v-model="inputDialog.formData"
      v-loading="inputDialog.loading"
      :fields="dynamicSupervisionFields"
      :form-config="inputDialog.config"
      :buttons="inputDialog.buttons"
      @cancel="inputDialog.visible = false"
    >
      <div slot="entList">
        <el-button size="medium" type="primary" @click="showEntList = true">查看主体名单<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
      </div>
      <div slot="contactPhone" slot-scope="scope">
        <el-input
          :value="scope.formData.contactPhone"
          @input="val => scope.formData.contactPhone = val"
        >
        </el-input>
      </div>
      <div slot="mobilePhone" slot-scope="scope">
        <el-input
          :value="scope.formData.mobilePhone"
          @input="val => scope.formData.mobilePhone = val"
        >
        </el-input>
      </div>
      <div slot="opinion" slot-scope="scope">
        <el-input
          v-model="scope.formData.opinion"
          type="textarea"
          :rows="1"
        />
        <div style="margin-top: 10px;">
          <span style="margin-right: 10px;">常用语:</span>
          <el-select v-model="scope.formData.opinion_select" @change="(value) => {scope.formData.opinion = value}">
            <el-option v-for="item in commonList" :key="item.value" :value="item.label" :label="item.commonlanguage" />
          </el-select>
        </div>
      </div>
    </EasyForm>

    <el-dialog
      title="核查主体名单"
      :visible.sync="showEntList"
      width="90%"
    >
      <span v-if="inputDialog.formData.checkAddress" style="color:red;">这批核查主体的同一地址为：{{inputDialog.formData.checkAddress}}</span>
      <EasyTable
        ref="entListRef"
        v-model="entList"
        :table-config="tableConfig"
        :fields="tableFields"
        :buttons="tableButtons"
        :total="tableTotal"
        :selected.sync="selected"
        :emit-current-change-on-create="true"
        @current-change="loadEntListData"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsualInspectInfo,
  tSUsualInspectListFile,
  tSUsualInspectUpdate,
  tSUsualInspectEntList,
  removeTSUsualInspectEntList, addContactLogByEntNo
} from '@/api/market'
import EasyTable from '@/components/EasyTable'
import EasyForm from '@/components/EasyForm'
import FakeProgress from '@/components/FakeProgress'
import dynamicSupervisionBase from '@/views/market/dynamicsupervision/index'
import { Eye } from 'element-ui'
export default {
  components: {
    EasyTable,
    EasyForm,
    FakeProgress,
    View: Eye
  },
  name: 'Inspect',
  mixins: [dynamicSupervisionBase],
  data() {
    return {
      bizSeq: '',
      showEntList: false,
      commonList: this.$util.getCommonWords(JSON.parse(sessionStorage.getItem('user')).primaryKey).filter((item) => {
        return item.module === '市场所协同'
      }),
      entList: [],
      selected: [],
      tableFields: [
        {
          prop: 'pripid',
          type: 'string',
          label: '企业主键'
        },
        {
          prop: 'uscc',
          type: 'string',
          label: '统一社会信用代码',
          showInTable: true
        },
        {
          prop: 'entName',
          type: 'string',
          label: '企业名称',
          showInTable: true
        },
        {
          prop: 'legalName',
          type: 'string',
          label: '法定代表人',
          showInTable: true
        },
        {
          prop: 'dom',
          type: 'string',
          label: '住所',
          showInTable: true
        },
        {
          prop: 'regStateCn',
          type: 'string',
          label: '企业状态',
          showInTable: true
        },
        {
          prop: 'regOrgCn',
          type: 'string',
          label: '登记机关',
          showInTable: true
        },
        {
          prop: 'supOrgCn',
          type: 'string',
          label: '属地监管机关',
          showInTable: true
        }
      ],
      tableTotal: 0,
      tableConfig: {
        selection: false,
        selectionWidth: '55',
        showPagination: true,
        tableProps: {
          border: true,
          headerCellStyle: { background: '#8cc3fb', color: '#fff' }
        },
        tableListeners: {
          'sort-change': ({ column, prop, order }) => {
            // this.sortBy = prop
            // this.asc = order === 'ascending'
            // this.$refs.entListRef.reset()
          }
        },
        rowKey: 'pripid'
      },
      tableButtons: [
        {
          label: '删除',
          type: 'text',
          loading: false,
          show: true,
          disabled: false,
          position: 'row', // header | row
          handler: (scope, button, easyTableInstance) => {
            this.delEnt(scope, button, easyTableInstance)
          }
        }
      ],
      inputDialog: {
        visible: false,
        formData: {},
        loading: false,
        config: {
          labelPosition: 'right',
          labelWidth: '130px',
          // gutter: 20,
          readOnly: false,
          submitPosition: 'center', // 页脚按钮位置
          showValidMessage: true // 校验失败时是否使用Message显示提示错误消息
        },
        buttons: [
          {
            label: '保存',
            type: 'primary',
            loading: false,
            show: (scope) => {
              return !scope.formConfig.readOnly
            },
            handler: (formData, button, easyFormInstance) => {
              easyFormInstance.submitForm().then((formData) => {
                this.updateInspect(formData, button, easyFormInstance)
              })
            }
          },
          {
            label: '返回',
            loading: false,
            show: (scope) => {
              return !scope.formConfig.readOnly
            },
            handler: (formData, button, easyFormInstance) => {
              this.$router.back()
            }
          }
        ]
      }
    }
  },
  methods: {
    // 获取脱敏显示
    getDisplayPhone(scope) {
      const phone = scope?.formData?.contactPhone || ''
      if (!phone) return ''

      // 处理手机号码 (11位数字)
      if (/^\d{11}$/.test(phone)) {
        return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }

      // 处理带区号的固定电话 (例如: 010-12345678 或 02112345678)
      if (/^\d{3,4}-?\d{7,8}$/.test(phone)) {
        // 提取区号和号码部分
        const parts = phone.includes('-') ? phone.split('-') : [phone.substring(0, 3), phone.substring(3)]
        const areaCode = parts[0]
        let numberPart = parts[1]

        // 隐藏号码部分的中间4位
        if (numberPart.length >= 7) {
          numberPart = numberPart.replace(/(\d{3})\d{4}(\d{0,4})/, '$1****$2')
        }

        return parts.length > 1 ? `${areaCode}-${numberPart}` : `${areaCode}${numberPart}`
      }

      // 处理其他格式的电话号码 (默认隐藏中间部分)
      const length = phone.length
      if (length > 7) {
        const start = Math.floor(length / 3)
        const end = Math.min(start + 4, length - 3)
        return phone.substring(0, start) + '****' + phone.substring(end)
      }

      // 短号码不做处理或自定义处理逻辑
      return phone
    },
    showFullPhone: function(scope) {
      this.$alert(scope?.formData?.contactPhone, '完整号码', {
        confirmButtonText: '关闭'
      })
      // eslint-disable-next-line no-empty
      if (scope?.formData?.contactPhone) {
        // 调用日志方法，传递所有必要参数
        addContactLogByEntNo({
          pripid: scope?.formData?.priPId,
          originalValue: scope?.formData?.contactPhone // 原始值
        }).then(res => {
          if (res.code === 0) {
            // 成功处理
          }
        }).catch(err => {
          console.error('记录日志失败:', err)
        })
      }
    },
    // 获取脱敏显示
    getDisplayPhoneb(scope) {
      const phone = scope?.formData?.contactPhone || ''
      if (!phone) return ''

      // 处理手机号码 (11位数字)
      if (/^\d{11}$/.test(phone)) {
        return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }

      // 处理带区号的固定电话 (例如: 010-12345678 或 02112345678)
      if (/^\d{3,4}-?\d{7,8}$/.test(phone)) {
        // 提取区号和号码部分
        const parts = phone.includes('-') ? phone.split('-') : [phone.substring(0, 3), phone.substring(3)]
        const areaCode = parts[0]
        let numberPart = parts[1]

        // 隐藏号码部分的中间4位
        if (numberPart.length >= 7) {
          numberPart = numberPart.replace(/(\d{3})\d{4}(\d{0,4})/, '$1****$2')
        }

        return parts.length > 1 ? `${areaCode}-${numberPart}` : `${areaCode}${numberPart}`
      }

      // 处理其他格式的电话号码 (默认隐藏中间部分)
      const length = phone.length
      if (length > 7) {
        const start = Math.floor(length / 3)
        const end = Math.min(start + 4, length - 3)
        return phone.substring(0, start) + '****' + phone.substring(end)
      }

      // 短号码不做处理或自定义处理逻辑
      return phone
    },
    showFullPhoneb(scope) {
      this.$alert(scope?.formData?.mobilePhone, '完整号码', {
        confirmButtonText: '关闭'
      })
      // eslint-disable-next-line no-empty
      if (scope?.formData?.mobilePhone) {
        // 调用日志方法，传递所有必要参数
        addContactLogByEntNo({
          pripid: scope?.formData?.priPId,
          originalValue: scope?.formData?.mobilePhone // 原始值
        }).then(res => {
          if (res.code === 0) {
            // 成功处理
          }
        }).catch(err => {
          console.error('记录日志失败:', err)
        })
      }
    },
    // 删除企业
    delEnt(scope) {
      removeTSUsualInspectEntList(scope.row.id).then(res => {
        this.$message.warning('删除成功')
        this.$refs.entListRef.reset()
      })
    },
    loadEntListData({ pageParam, instance }) {
      instance.loading = true
      tSUsualInspectEntList({
        'curPage': pageParam.current,
        'customParamMap': {},
        'inParamMap': {},
        'likeParamMap': {},
        'pageSize': pageParam.size,
        'paramMap': {
          bizSeq: this.bizSeq
        }
      }).then((res) => {
        const { code, data } = res
        if (code === 0) {
          this.entList = data.records
          this.tableTotal = data.total
        }
      }).finally(() => {
        instance.loading = false
      })
    },
    updateInspect(formData, button, easyFormInstance) {
      // 录入检查
      button.loading = true
      // let domMsg = ''
      return tSUsualInspectUpdate(formData).then((res) => {
        const { code, data } = res
        if (code !== 0) {
          throw res
        }
        // if(code == 0 && data != null && data.msg){
        //   domMsg = data.msg
        //   this.$confirm(data.msg, '提示', {
        //     type: 'warning'
        //   }).then(() => {this.$router.push('/market/dynamicsupervision')})
        // }
      }).then(() => {
        // if(domMsg == ''){
        //   this.$router.push('/market/dynamicsupervision')
        // }
        this.$router.push('/market/dynamicsupervision')
      }).finally(() => {
        button.loading = false
      })
    },
    init() {
      this.inputDialog.visible = true
      this.inputDialog.loading = true

      getUsualInspectInfo(this.bizSeq).then(res => {
        const inspectInfo = res.data

        tSUsualInspectListFile({ id: this.bizSeq }).then((res) => {
          const { code, data } = res
          if (code !== 0) {
            throw res
          }
          this.inputDialog.formData = {
            ...inspectInfo,
            files: []
          }
          this.$set(this.inputDialog.formData, 'files', data.filter((file) => {
            return file.attachtype === '2'
          }).map((item) => {
            return {
              ...item,
              name: item.filename
            }
          }))
          this.$set(this.inputDialog.formData, 'files0', data.filter((file) => {
            return file.attachtype === '1'
          }).map((item) => {
            return {
              ...item,
              name: item.filename
            }
          }))
        }).finally(() => {
          this.inputDialog.loading = false
        })
      }).finally(() => {
        this.inputDialog.loading = false
      })
    }
  },
  computed: {
    _currentId() {
      return this.bizSeq
    }
  },
  created() {
    this.bizSeq = this.$route.query.bizseq
    this.init()
  }
}
</script>

<style scoped>

</style>
