<template>
  <el-dialog :title="modalTitle" :visible.sync="visible" width="95%" class="import-modal-wrap" append-to-body>
    <section class="common-header-title">上传文件</section>
    <el-upload
      class="import-upload"
      ref="upload"
      :limit="1"
      action="none"
      accept=".xlsx, .xls"
      :on-change="onUploadChange"
      :on-remove="handleRemove"
      :auto-upload="false"
      :fileList="fileList"
      drag
    >
      <svg-icon icon-class="upload-cloud" class="upload-cloud" />
      <div class="el-upload__text">
        <span style="font-size: 14px; color: #666666; line-height: 14px">仅允许导入xls、xlsx格式文件, 文件大小不能超过60MB</span>
        <el-button size="small" type="primary" class="upload-btn">上传文件</el-button>
        <el-button type="text" icon="el-icon-download" style="font-size: 14px; margin-left: 0" @click.stop="downloadFlie">下载模板</el-button>
        <span
          v-if="fileDataArr.length > 0"
          class="file-name"
          :class="{ 'is-show-del': isDelete }"
          @mouseenter="isDelete = !isDelete"
          @mouseleave="isDelete = !isDelete"
          >{{ getFileName() }} <i class="el-icon-close" @click.stop="delFile"></i
        ></span>
      </div>
      <div class="el-upload__tip text-center" slot="tip"></div>
    </el-upload>
    <div class="select-cnt">
      <span>客户类型</span>
      <el-select v-model="uploadClientType" disabled placeholder="请选择客户类型" clearable style="margin-left: 36px">
        <el-option v-for="(item, index) in clientTypeOptions" :key="index" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </div>
    <section class="common-header-title" @click="onPreview">预览</section>
    <el-form :inline="true" autoComplete="on" :model="formObj" ref="formObj">
      <section class="list-header">
        <p>
          <span>客户类型</span>
          <span>客户号</span>
          <span>客户内码</span>
          <span>证件类型</span>
          <span>客户名称</span>
          <span>证件号</span>
          <span>备注</span>
          <template v-if="['2', '1'].includes(custType)">
            <span>注册地址</span>
            <span>经营地址</span>
          </template>
          <template v-else>
            <span>家庭地址</span>
            <span>工作地址</span>
            <span>户籍地址</span>
          </template>
          <span>所在行业</span>
          <span>操作</span>
        </p>
        <el-empty :image-size="50" v-if="formObj.tableData.length === 0"></el-empty>
        <ul v-else>
          <li class="formObj-form-item" v-for="(item, ind) in formObj.tableData" :key="item.key">
            <section class="form-vl">
              <el-form-item class="form-item form-item-custType">
                <span>{{ item.custType }}</span>
              </el-form-item>
              <el-form-item
                class="form-item form-item-custId"
                :prop="'tableData.' + ind + '.custId'"
                :rules="{ required: true, message: '客户号为空', trigger: 'blur' }"
              >
                <el-input v-if="item.isEdit" clearable v-model="item.custId" placeholder="请输入" class="input-name"></el-input>
                <span v-else>{{ item.custId }}</span>
              </el-form-item>
              <el-form-item
                class="form-item form-item-custIsn"
                :prop="'tableData.' + ind + '.custIsn'"
                :rules="{ required: true, message: '客户内码为空', trigger: 'blur' }"
              >
                <el-input v-if="item.isEdit" clearable v-model="item.custIsn" placeholder="请输入" class="input-name"></el-input>
                <span v-else>{{ item.custIsn }}</span>
              </el-form-item>

              <el-form-item
                class="form-item form-item-custIdType"
                :prop="'tableData.' + ind + '.custIdType'"
                :rules="{ required: true, message: '证件类型为空', trigger: 'blur' }"
              >
                <el-input v-if="item.isEdit" clearable v-model="item.custIdType" placeholder="请输入" class="input-name"></el-input>
                <span v-else>{{ item.custIdType }}</span>
              </el-form-item>
              <el-form-item
                class="form-item form-item-anchorName"
                :prop="'tableData.' + ind + '.anchorName'"
                :rules="{ required: true, message: '客户名称为空', trigger: 'blur' }"
              >
                <el-input v-if="item.isEdit" clearable v-model="item.anchorName" placeholder="请输入" class="input-name"></el-input>
                <span v-else>{{ item.anchorName }}</span>
              </el-form-item>
              <el-form-item
                class="form-item form-item-legalId"
                :prop="'tableData.' + ind + '.legalId'"
                :rules="{ required: true, message: '证件号为空', trigger: 'blur' }"
              >
                <el-input v-if="item.isEdit" clearable v-model="item.legalId" placeholder="请输入" class="input-name"></el-input>
                <span v-else>{{ item.legalId }}</span>
              </el-form-item>
              <el-form-item class="form-item form-item-anchorRemark">
                <el-input v-if="item.isEdit" clearable v-model="item.anchorRemark" placeholder="请输入" class="input-name"></el-input>
                <span v-else>{{ item.anchorRemark }}</span>
              </el-form-item>
              <template v-if="['2', '1'].includes(custType)">
                <el-form-item class="form-item form-item-addressName">
                  <el-input v-if="item.isEdit" clearable v-model="item.addressZc" placeholder="请输入" class="input-name"></el-input>
                  <span v-else>{{ item.addressZc }}</span>
                </el-form-item>
                <el-form-item class="form-item form-item-addressName">
                  <el-input v-if="item.isEdit" clearable v-model="item.addressJy" placeholder="请输入" class="input-name"></el-input>
                  <span v-else>{{ item.addressJy }}</span>
                </el-form-item>
              </template>
              <template v-else>
                <el-form-item class="form-item form-item-addressName">
                  <el-input v-if="item.isEdit" clearable v-model="item.addressJt" placeholder="请输入" class="input-name"></el-input>
                  <span v-else>{{ item.addressJt }}</span>
                </el-form-item>
                <el-form-item class="form-item form-item-addressName">
                  <el-input v-if="item.isEdit" clearable v-model="item.addressGz" placeholder="请输入" class="input-name"></el-input>
                  <span v-else>{{ item.addressGz }}</span>
                </el-form-item>
                <el-form-item class="form-item form-item-addressName">
                  <el-input v-if="item.isEdit" clearable v-model="item.addressHj" placeholder="请输入" class="input-name"></el-input>
                  <span v-else>{{ item.addressHj }}</span>
                </el-form-item>
              </template>
              <el-form-item class="form-item form-item-belongBusiness">
                <el-input v-if="item.isEdit" clearable v-model="item.belongBusiness" placeholder="请输入" class="input-name"></el-input>
                <span v-else>{{ item.belongBusiness }}</span>
              </el-form-item>
              <el-form-item>
                <el-button type="text" @click="onEdit(item, ind)" style="margin-left: 8px">{{ !item.isEdit ? '编辑' : '保存' }}</el-button>
                <el-button type="text" :disabled="formObj.tableData.length <= 1" @click="onDel(ind)">删除</el-button>
              </el-form-item>
            </section>
          </li>
        </ul>
      </section>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="submitUpload" :disabled="fileDataArr.length === 0 || formObj.tableData.length === 0"
        >确 定</el-button
      >
    </div>
    <status-modal ref="statusModal" :statusType="statusType" :tableData="errorList" :custType="custType" @onPreview="previewError"></status-modal>
    <error-list-modal ref="errorListModal" :tableData="errorList"></error-list-modal>
  </el-dialog>
</template>

<script>
import { exportModel, importQyModel, importGrModel, exportPersonModel, returnGrModel, returnQyModel } from '@/api/grid/anchor.js'
import { downloadFiles } from '@/utils'
import { clientTypeOptions, custTypeMap } from './../constant-info'
import StatusModal from './status-modal'
import ErrorListModal from './error-list-modal'
import { isEmpty, cloneDeep } from 'lodash'

const initMap = {
  custType: '',
  anchorName: '',
  custIdType: '',
  legalId: '',
  addressName: '',
  belongBusiness: '',
  analysisResults: '',
  address: '',
  anchorRemark: '',
  addressTypeOptions: []
}

export default {
  components: {
    StatusModal,
    ErrorListModal
  },
  props: {
    modalTitle: {
      type: String,
      default: ''
    },
    defaultUploadClientType: {
      type: String,
      default: ''
    },
    custType: {
      type: String,
      default: ''
    }
  },
  computed: {
    userid() {
      return localStorage.getItem('userid')
    }
  },
  watch: {
    visible(val) {
      val && this.getInitData()
    }
  },
  data() {
    return {
      isDelete: false,
      visible: false,
      statusType: '',
      clientTypeOptions,
      uploadClientType: '',
      pageLoading: false,
      tableData: [],
      errorList: [],
      btnLoading: false,
      fileList: [],
      formObj: {
        tableData: [cloneDeep(initMap)]
      },
      fileDataArr: []
    }
  },
  methods: {
    onPreview() {
      this.statusType = 'warning'
      this.$refs.statusModal.onOpen()
    },
    delFile() {
      this.clearFiles()
      this.fileDataArr = []
    },
    previewError() {
      this.$refs.errorListModal.onOpen()
    },
    onUploadChange(file, fileList) {
      const isLt60M = file.size / 1024 / 1024 < 60
      if (!isLt60M) {
        this.$message.error('上传单个文件大小不能超过 60MB!')
        this.clearFiles()
        return false
      } else {
        if (fileList.length > 0) {
          this.fileDataArr = cloneDeep(fileList)
          this.onSuccess(file.raw)
        }
        fileList.splice(0, 1)
        // this.fileList = []
        console.log(this.fileDataArr, '====')
        console.log(isLt60M, this.fileList, file)
      }
    },
    onEdit(row, tag) {
      this.$set(this.formObj.tableData[tag], 'isEdit', !this.formObj.tableData[tag].isEdit)
    },
    onDel(index) {
      this.formObj.tableData.splice(index, 1)
    },
    clearFiles() {
      this.fileList = []
      this.fileDataArr = []
      this.$refs.upload?.clearFiles()
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    onSuccess(file) {
      const apiUrl = ['2', '1'].includes(this.custType) ? returnQyModel : returnGrModel
      const formData = new FormData()
      formData.append('file', file)
      apiUrl(formData).then((res) => {
        if (res.code === 200) {
          const newArr = []
          res?.data?.map((item) => {
            if (item.custType === custTypeMap[this.custType]) {
              newArr.push({
                ...item,
                isEdit: false
              })
            }
          }) || []
          this.formObj.tableData = newArr
        }
      })
    },
    getInitData() {
      this.clearFiles()
      this.uploadClientType = this.defaultUploadClientType
    },
    getTableData() {},
    onClose() {
      this.formObj.tableData = []
      this.visible = false
    },
    downloadFlie() {
      const apiUrl = ['2', '1'].includes(this.custType) ? exportModel : exportPersonModel
      apiUrl().then((res) => {
        downloadFiles(res, `${custTypeMap[this.custType]}锚点导入模板_${new Date().getTime()}.xlsx`)
      })
    },
    submitUpload() {
      this.btnLoading = true
      const apiUrl = ['2', '1'].includes(this.custType) ? importQyModel : importGrModel

      apiUrl(this.formObj.tableData)
        .then((res) => {
          if (res.code === 200) {
            if (res.msg === '全部失败') {
              this.clearFiles()
              this.statusType = 'error'
              this.$refs.statusModal.onOpen()
            } else if (res.msg === '部分成功' && !isEmpty(res.data)) {
              this.statusType = 'warning'
              this.errorList = res.data
              this.$refs.statusModal.onOpen()
              this.$emit('onRefreshTable')
              this.onClose()
            } else {
              this.statusType = 'success'
              this.$refs.statusModal.onOpen()
              this.$emit('onRefreshTable')
              this.onClose()
            }
          }
        })
        .catch((err) => console.error(err))
        .finally(() => {
          this.btnLoading = false
        })
    },
    onOpen() {
      this.visible = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    getFileName() {
      if (isEmpty(this.fileDataArr)) {
        return ''
      }
      return this.fileDataArr[0].name
    }
  }
}
</script>

<style lang="scss" scoped>
.import-upload {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  ::v-deep .el-upload {
    width: 700px;
    .el-upload-dragger {
      background-color: #f7f8fa;
      border: 1px dashed #cccccc;
      width: 100%;
      height: 288px;
      border-radius: 2px;
    }
    .el-icon-upload {
      margin: 40px 0 13px;
    }
    .upload-btn {
      margin: 24px 0 16px 0;
    }
    .el-upload__text {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
  }
}
.common-header-title {
  margin-bottom: 24px;
}
.select-cnt {
  width: 700px;
  margin: 20px auto 50px auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  > span {
    display: inline-block;
    width: 56px;
  }
  .el-select {
    flex: 1;
  }
}
.el-upload__tip {
  margin-top: 20px;
}
.list-header {
  clear: both;
  > p {
    font-size: 0;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    > span {
      font-size: 14px;
      color: #212121;
      display: inline-block;
      letter-spacing: normal;
      word-spacing: normal;
      width: 10%;
      margin-right: 12px;
    }
  }
  ul {
    max-height: 50vh;
    margin: 0;
    list-style: none;
    padding: 0;
    .form-vl {
      display: flex;
      align-items: center;
      ::v-deep .el-form-item {
        margin-right: 12px;
        margin-bottom: 0;
        width: 10%;
        .el-form-item__content {
          display: flex;
          span {
            display: inline-block;
            max-width: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        &.is-error .el-form-item__content {
          width: 62%;
        }
      }
    }
    .el-icon-remove-outline,
    .el-icon-circle-plus-outline {
      font-size: 24px;
      cursor: pointer;
    }
    .disabeld-icon {
      color: #dcdfe6;
      cursor: not-allowed;
      pointer-events: none;
    }
  }
}
.file-name {
  color: #666666;
  font-size: 12px;
  font-weight: 400;
  margin-top: 20px;
  cursor: default;
  .el-icon-close {
    margin-left: 50px;
    visibility: hidden;
    cursor: pointer;
  }
  &.is-show-del {
    .el-icon-close {
      visibility: visible;
    }
  }
}
.upload-cloud {
  width: 64px;
  height: 64px;
  margin: 40px 0 13px 0;
}
</style>

<style lang="scss">
.import-modal-wrap {
  .el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
  }
}
</style>