/**
 * 为方便用作其他页面展示，抽离公共参数
 */
import { tSUsualInspectDelFile, tSUsualInspectListFile } from '@/api/market'
import { parseTime } from '@/utils'
import { downLoadHistoryFile } from '@/api/abnormal'

export default {
  data() {
    return {
      dynamicSupervisionFields: [
        {
          prop: 'entList',
          label: '现场核查任务名单',
          type: 'slot',
          span: 24,
          config: {
            readOnly: false
          },
          showInForm: (scope) => {
            return scope.formData.busType === '2'
          },
          slotName: 'entList'
        },
        {
          prop: 'uscc',
          label: '统一社会信用代码',
          type: 'view',
          span: 12,
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          }
        },
        {
          prop: 'regNo',
          label: '注册号',
          type: 'view',
          span: 12,
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          }
        },
        {
          prop: 'entName',
          label: '主体名称',
          type: 'view',
          span: 12,
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          },
          showInTable: true
        },
        {
          prop: 'dom',
          label: '经营地址',
          type: 'view',
          span: 12,
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          },
          showInTable: true,
          tableProps: {
            sortable: 'custom'
          }
        },
        {
          prop: 'legalName',
          label: '法定代表人/负责人',
          type: 'view',
          span: 12,
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          },
          showInTable: true
        },
        {
          prop: 'contacts',
          label: '联系人',
          type: 'input',
          span: 12,
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          }
        },
        {
          prop: 'contactPhone',
          label: '联系电话',
          type: 'slot',
          slotName: 'contactPhone',
          span: 12,
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          },
          rule: [
            {
              pattern: /(^[0-9]{3,4}(-)[0-9]{7,8}(-[0-9]{1,4})?$)|(^1[3-9]\d{9}$)/,
              message: '联系电话格式错误',
              trigger: 'blur'
            }
          ]
        },
        {
          prop: 'mobilePhone',
          label: '手机号码',
          type: 'slot',
          slotName: 'mobilePhone',
          span: 12,
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          },
          rule: [
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '手机号码格式不正确',
              trigger: 'blur'
            }
          ]
        },
        {
          prop: 'scope',
          label: '经营范围',
          type: 'view',
          span: 24,
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          }
        },
        {
          prop: 'actualScope',
          label: '实际经营项目',
          showInForm: (scope) => {
            return scope.formData.busType === '1'
          },
          type: 'input',
          span: 24,
          formProps: {
            type: 'textarea',
            autosize: { minRows: 4, maxRows: 6 }
          }
        },
        // {
        //   prop: 'remarks',
        //   label: '实际经营范围备注',
        //   showInForm: true,
        //   type: 'input',
        //   span: 24
        // },
        // {
        //   prop: 'area',
        //   label: '实际经营面积',
        //   type: 'input',
        //   span: 12,
        //   append: '平方米',
        //   showInForm: true
        // },
        // {
        //   prop: 'busMode',
        //   label: '经营方式',
        //   type: 'input',
        //   span: 12,
        //   showInForm: true
        // },
        // {
        //   prop: 'inspectType',
        //   label: '检查类型',
        //   showInForm: true,
        //   type: 'view',
        //   span: 12,
        //   showInTable: true
        // },
        {
          prop: 'inspectDate',
          label: '检查日期',
          type: 'date-picker',
          span: 12,
          showInForm: true,
          required: true,
          defaultValue: () => {
            return parseTime(new Date(), '{yyyy}-{mm}-{dd} {hh}:{ii}:{ss}')
          },
          formProps: {
            type: 'date',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            format: 'yyyy-MM-dd'
          }
        },
        {
          prop: 'inspectExpireDate',
          label: '检查期限',
          type: 'date-picker',
          span: 12,
          isView: true,
          viewer: (val, scope) => {
            return `${scope.formData.inspectStartDate || ''} - ${scope.formData.inspectExpireDate || ''}`
          },
          showInForm: true,
          showInTable: true,
          praseValue: (val) => {
            if (Array.isArray(val)) {
              return val
            } else {
              return parseTime(val, '{yyyy}-{mm}-{dd}')
            }
          },
          defaultValue: () => {
            return []
          },
          tableProps: {
            sortable: 'custom'
          },
          formProps: {
            type: 'date',
            valueFormat: 'yyyy-MM-dd',
            format: 'yyyy-MM-dd'
          }
        },
        {
          prop: 'inspectContent',
          label: '现场核查情况',
          type: 'input',
          span: 24,
          showInForm: true,
          required: true,
          formProps: {
            type: 'textarea',
            maxlength: '800',
            'show-word-limit': 'true',
            autosize: { minRows: 4, maxRows: 6 }
          }
        },
        {
          type: 'radio',
          prop: 'isComplained',
          label: '是否予以审慎监管特殊标记',
          showInForm: JSON.parse(sessionStorage.getItem('user')).orgCode.startsWith('440126'),
          showInTable: false,
          span: 24,
          required: JSON.parse(sessionStorage.getItem('user')).orgCode.startsWith('440126'),
          options: [
            { label: '否', value: '0' },
            { label: '是', value: '1' }
          ]
        },
        // {
        //   type: 'radio',
        //   prop: 'inspectResult',
        //   label: '检查结果',
        //   showInForm: true,
        //   showInTable: false,
        //   span: 24,
        //   required: true,
        //   options: [
        //     { label: '未发现问题', value: '1' },
        //     { label: '未按规定公示应当公示的信息', value: '2' },
        //     { label: '公示信息隐瞒真实情况弄虚作假', value: '3' },
        //     { label: '通过登记住所（经营场所）无法联系', value: '4' },
        //     { label: '发现问题已责令改正', value: '5' },
        //     { label: '不配合检查情节严重', value: '6' },
        //     { label: '未发现开展本次检查涉及的经营活动', value: '7' },
        //     { label: '发现问题待后续处理', value: '8' }
        //   ]
        // },
        {
          type: 'checkbox',
          prop: 'inspectResult',
          label: '检查结果',
          showInForm: true,
          showInTable: false,
          span: 24,
          defaultValue: () => {
            return []
          },
          formProps: (scope) => {
            return {
              max: scope.formData.busType === '2' ? 1 : Infinity
            }
          },
          required: true,
          options: (scope) => {
            if(scope.formData.source === '批量吊销'){
              return [
                {
                  label: '未发现问题',
                  value: '1',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['6'].includes(item)
                    })
                  }
                },
                { label: '通过登记住所（经营场所）无法联系',
                  value: '4',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['1', '6'].includes(item)
                    })
                  }
                }
              ]
            } else {
              return [
                {
                  label: '未发现问题',
                  value: '1',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['6'].includes(item)
                    })
                  }
                },
                {
                  label: '未按规定公示应当公示的信息',
                  value: '2',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['1', '6'].includes(item)
                    })
                  }
                },
                {
                  label: '公示信息隐瞒真实情况弄虚作假',
                  value: '3',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['1', '6'].includes(item)
                    })
                  }
                },
                { label: '通过登记住所（经营场所）无法联系',
                  value: '4',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['1', '6'].includes(item)
                    })
                  }
                },
                {
                  label: '发现问题已责令改正',
                  value: '5',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['1', '6'].includes(item)
                    })
                  }
                },
                {
                  label: '不配合检查情节严重',
                  value: '6',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['1'].includes(item)
                    })
                  }
                },
                {
                  label: '未发现开展本次检查涉及的经营活动',
                  value: '7',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['1', '6'].includes(item)
                    })
                  }
                },
                {
                  label: '发现问题待后续处理',
                  value: '8',
                  disabled: (scope) => {
                    return scope.formData.inspectResult.some((item) => {
                      return ['1', '6'].includes(item)
                    })
                  }
                }
              ]
            }
          },
          valueFormat: (value) => {
            return value.sort((a, b) => {
              return parseInt(a) - parseInt(b)
            }).join(',')
          },
          praseValue: (value) => {
            return typeof value === 'string' ? value.split(',') : value
          },
          formListeners: (scope) => {
            return {
              change: (value) => {
                if (value.length !== 1 && value.includes('1')) {
                  this.$set(scope.formData, 'inspectResult', ['1'])
                }
                if (value.length !== 1 && value.includes('6')) {
                  this.$set(scope.formData, 'inspectResult', ['6'])
                }
              }
            }
          }
        },
        {
          type: 'upload',
          label: '责令整改通知书',
          required: true,
          prop: 'files0',
          span: 24,
          showInForm: (scope) => {
            return scope.formData.inspectResult.some((item) => {
              return ['5'].includes(item)
            })
          },
          defaultValue: () => {
            return []
          },
          uploadData: () => {
            return {
              id: this._currentId,
              attachType: '1'
            }
          },
          formProps: {
            action: `${process.env.VUE_APP_BASE_API}/market/tSUsualInspect/upload`,
            autoUpload: true,
            onPreview: (file) => {
              if (file.attachmentid) {
                window.open(`${process.env.VUE_APP_BASE_API}/market/tSUsualInspect/downloadFile?fileId=${file.attachmentid}`)
              } else {
                window.open(URL.createObjectURL(file.raw))
              }
            }
          }
        },
        {
          prop: 'opinion',
          label: '备注',
          type: 'slot',
          span: 24,
          showInForm: true,
          slotName: 'opinion'
        },
        {
          prop: 'backOpinion',
          label: '回退意见',
          type: 'view',
          span: 24,
          showInForm: ({ formData, formConfig, componentName }) => {
            return formData.backOpinion !== null
          }
        },
        {
          prop: 'inspector',
          label: '检查人',
          type: 'view',
          span: 12,
          showInForm: true
        },
        {
          prop: 'helper',
          label: '协查人',
          showInForm: true,
          type: 'input',
          span: 12
        },
        {
          prop: 'files',
          label: '材料上传',
          showInForm: true,
          type: 'upload',
          defaultValue: [],
          span: 24,
          tips: ({ formData }) => {
            return `须上传现场照片、现场检查记录、询问笔录、物管证明等证据材料，可选择上传其他辅助材料,支持上传的文件格式有：*.jpg,*.gif,*.doc,*.xls,*.txt,*.pdf,*.docx,*.wps,*.xlsx,*.et`
          },
          uploadData: () => {
            return {
              id: this._currentId,
              attachType: '2'
            }
          },
          formProps: {
            action: `${process.env.VUE_APP_BASE_API}/market/tSUsualInspect/upload`,
            autoUpload: true,
            accept: '.jpg,.gif,.doc,.xls,.txt,.pdf,.docx,.wps,.xlsx,.et',
            onPreview: (file) => {
              if (file.createtype === '3') {
                console.log('历史数据附件')
                // 历史数据附件
                downLoadHistoryFile(file.attachmentid).then(res => {
                  const data = res
                  if (!data) {
                    return
                  }
                  const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' }))
                  // window.open(url)
                  const link = document.createElement('a')
                  link.style.display = 'none'
                  link.href = url
                  link.setAttribute('download', file.filename)
                  // document.body.appendChild(link)
                  link.click()
                }).catch(req => {
                  console.log('下载失败', req)
                })
              } else {
                if (file.attachmentid) {
                  window.open(`${process.env.VUE_APP_BASE_API}/market/tSUsualInspect/downloadFile?fileId=${file.attachmentid}`)
                } else {
                  window.open(URL.createObjectURL(file.raw))
                }
              }
            },
            beforeRemove: (file, fileList) => {
              return new Promise((resolve, reject) => {
                this.$confirm(`确认要删除文件: ${file.filename}`, '提示', {
                  callback: (action) => {
                    if (action === 'confirm') {
                      if (file.attachmentid) {
                        resolve(
                          tSUsualInspectDelFile({
                            id: file.attachmentid
                          }).then((res) => {
                            if (res.code === 0) {
                              this.$message.success('删除成功')
                            } else {
                              throw res
                            }
                          })
                        )
                      }
                    } else {
                      reject()
                    }
                  }
                })
              })
            }
          },
          required: true
        },
        {
          type: 'view',
          prop: 'status',
          label: '状态',
          showInTable: true,
          tableProps: {
            formatter: (row) => {
              let status_cn = ''
              if (row.status === '0') {
                status_cn = '待检查'
              } else if (row.status === '2') {
                status_cn = '列异回退'
              } else {
                status_cn = '已检查'
              }
              return status_cn
            }
          }
        },
        {
          type: 'view',
          prop: 'source',
          label: '来源',
          showInTable: true,
          tableProps: {
            formatter: (row) => {
              let label = ''
              this.sources.forEach(item => {
                if (row.source === item.value) {
                  label = item.label
                }
              })
              return label
            }
          }
        }
      ],
      inputDialog: {
        visible: false,
        formData: {},
        loading: false,
        config: {
          labelPosition: 'right',
          labelWidth: '130px',
          // gutter: 20,
          readOnly: false,
          submitPosition: 'center', // 页脚按钮位置
          showValidMessage: true // 校验失败时是否使用Message显示提示错误消息
        },
        buttons: []
      }
    }
  },
  methods: {
    dynamicSupervisionEvent(scope) {
      this.inputDialog.visible = true
      this.inputDialog.loading = true
      tSUsualInspectListFile({ id: scope.row.id }).then((res) => {
        const { code, data } = res
        if (code !== 0) {
          throw res
        }
        this.currentId = scope.row.id
        this.inputDialog.formData = scope.row
        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
          }
        }))
        this.$nextTick(() => {
          if (this.$refs.inputDialog) {
            this.$refs.inputDialog.clearValidate()
          }
        })
      }).finally(() => {
        this.inputDialog.loading = false
      })
    }
  }
}
