<template>
<el-collapse-transition>
  <div   class="ls-table-wrap">
    <div class="file-tips">
      <div>
        <el-button  @click="handleMore"
          type="primary" plain  size="mini" >
         <span v-if="isMore">收起</span>
         <span v-else>更多</span>
        </el-button>
        <el-button v-if="isMore"  @click="handleAddFile"
          type="primary" plain  size="mini" >新增文件</el-button>
      </div>
    </div>
    <el-table :data="fileTableData" ref="tableRef"
      :cell-style="cellStyle"
      highlight-current-row
      size="mini" stripe border >
      <el-table-column type="index" label="序号" width="50"  show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="fileTypeKey"  class-name="p0"
        label="资质文件" min-width="120" show-overflow-tooltip >
        <template  slot-scope="scope">
          <span v-if="scope.row.required" class="cFB62">*</span>
          <span class="c77FA">{{scope.row.fileTypeKey}}</span>
        </template>
      </el-table-column>
      <el-table-column  v-for="(item, index) in colunms" :key="index"
        :prop="item.prop"
        :label="item.label"
        :fixed="item.fixed"
        :formatter="formatter"
        :min-width="item.width"
        :show-overflow-tooltip="item.tooltip"
      >
      </el-table-column>
      <el-table-column label="操作" min-width="120" fixed="right" >
        <template  slot-scope="scope">
          <el-button v-if="scope.row.fileId && scope.row.status==1 "
            @click="editRowFile(scope.row)"
            type="text" >编辑</el-button>
          <el-button v-if="scope.row.fileId"
            @click="handleDelete(scope.row)"
            type="text" >删除</el-button>
          <el-button v-if="!scope.row.fileId"
          @click="addRowFile(scope.row, scope.$index)"
           type="text"  >添加</el-button>
        </template>
      </el-table-column>
    </el-table>

    <dig-file
      @getFileInfo="setFileInfo"
      :editFileType="editFileType"
      ref="digFileRef"
      :bus-id="cmInfo.id"
    >
    </dig-file>
  </div>
</el-collapse-transition>
</template>

<script>
import commonSelectList from '@/common/commonSelectList.js'
import digFile  from '@/pages/customer/public/components/dig-file.vue'
export default{
  name: 'document-info',
  components:{
    digFile,
  },
  created(){
    this.initDictData();
  },
  mounted(){

  },
  methods: {
    async initDictData(){
      this.qualificatDocList = await commonSelectList.dictDataGet(this, 'Crm_Qualification_Documents') || [];
    },
    async initFileList(){
      let FilelistPromise = this.getAttachFilelist();
      let fileList = await FilelistPromise || [];
      //1.根据条件，从资质文件数字字典数据中，标出必须上传的 资质文件
      this.moreFileData = [];
      this.qualificatDocList.forEach((item, i)=>{
        let obj = {};
        obj.fileTypeKey = item.key;
        obj.fileType = item.vaule;
        obj.uploadType = item.ext1;//备用字段区分是协议文件，或资质文件
        if(item.vaule == "businessHeat" ){  //营业执照
          obj.required = true;
        } else {
          obj.required = false;
        }
        obj.fileType != 'other' && this.moreFileData.push(obj);
      })
      //2.从 busId 筛查的文件数据中， 查找已上传的资质文件
      for(let i=0; i< fileList.length; i++){
        let item1 = fileList[i];
        //2.1有fileType 属性的是资质文件
        if( item1.fileType){
          if(item1.fileType != 'other'){
            for(let j=0; j<this.moreFileData.length; j++){
              let item2 = this.moreFileData[j];
              if(item1.fileType == item2.fileType){
                item1.fileTypeKey = item2.fileTypeKey;
                item1.required = item2.required;
                item1.uploadType = item2.uploadType;
                this.moreFileData.unshift(item1);
                break;
              }
            }
          }else{
            item1.required = false;
            this.moreFileData.push(item1);
          }
        }
      };
      //把已上传的文件，从添加操作中移出
      for(let i=0; i<this.moreFileData.length; i++){
        let item1 = this.moreFileData[i];
        for(let j=0; j<this.moreFileData.length; j++){
          let item2 = this.moreFileData[j];
          if( (item1.fileType == item2.fileType) && item1.fileId && !item2.fileId ){
            this.moreFileData.splice(j, 1);
            break;
          }
        }
      }

      if(this.isMore){
        this.fileTableData = this.moreFileData;
      }else{
        //3. 筛出必须上传文件, 展示文件
        this.setTableData();
      }
    },
    setTableData(){
      this.isMore = false;
      this.fileTableData = [];
      for(let i=0; i<this.moreFileData.length; i++){
        let item = this.moreFileData[i];
        if(item.required){
          this.fileTableData.push(item);
          continue;
        }
        if( this.cmInfo.placeId == 'China' &&
          (item.fileType == 'enterpriseCreditInvestigation' ||
          item.fileType == 'customsQualification')
        ){
          //企业征信&&海关资质 文件
          this.fileTableData.push(item);
        }
        if(this.cmInfo.customerClassifyId == 'agent' &&
           item.fileType == "agentAuthorizationAgreement"){
          //代理商授权协议
          this.fileTableData.push(item);
        }
      }
    },
    getAttachFilelist(){
      return new Promise((resolve, reject)=>{
         this.$ajax.post({
           domain: 'crmCmUrl',
           url: 'attachFiles.getAttachFilelist',
           data: {
             busId: this.cmInfo.id,
             modelId: '3110',
           },
           requestType: 'body',
           showLoad: false,
           success: function (res) {
             if (res.errorCode === 200) {
              let data = res.data;
              resolve(data);
             }
           }.bind(this),
           error: function (res) {
             this.$message.error( res.body.msg || res.msg);
             reject(res);
           }.bind(this)
         })
       }).catch((err)=>{
         console.log(err.data);
      })
    },
    handleMore(){
      this.isMore = !this.isMore;
      if(this.isMore){
        this.fileTableData = this.moreFileData;
      }else{
        this.setTableData();
      }
    },
    handleAddFile(){
      this.editFileType = true;
      this.$refs.digFileRef.openTitle = '新增文件';
      this.$refs.digFileRef.openType = 'add';
      this.$refs.digFileRef.visible = true;
    },
    addRowFile(row, i){
      this.editFileType = false;
      this.$refs.digFileRef.uploadType = row.uploadType;
      this.$refs.digFileRef.openTitle = '新增文件';
      this.$refs.digFileRef.paramForm.fileType = row.fileType;
      this.$refs.digFileRef.openType = 'add';
      this.$refs.digFileRef.visible = true;
    },
    editRowFile(row, i){
      this.editFileType = false;
      this.$refs.digFileRef.uploadType = row.uploadType;
      this.$refs.digFileRef.openTitle = '编辑文件';
      this.$refs.digFileRef.paramForm = JSON.parse(JSON.stringify(row));
      this.$refs.digFileRef.openType = 'edit';
      this.$refs.digFileRef.visible = true;
    },
    handleDelete(row){
      this.$confirm('确定提交?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( () => {
          this.$ajax.post({
            domain: 'crmCmUrl',
            url: 'attachFiles.deleteAttachFile',
            data: { id: row.id  },
            requestType: 'body',
            showLoad: true,
            success: function (res) {
              if (res.errorCode === 200) {
                this.initFileList();
                this.$message.success('删除成功');
              }
            }.bind(this),
            error: function (res) {
              this.$message.error( res.body.msg || res.msg);
            }.bind(this)
          })
      }).catch(() => { });
    },
    setFileInfo(f, i){
      this.initFileList();
    },
    formatter(row, column, cellValue, index){
      if(column.property == 'status'){
        if(row.status == 1){
          return '有效';
        }else if(row.status == 0){
          return '无效';
        } else {
          return '';
        }
      } else if(column.property == 'fileIndate'){
         if(row.fileIndate && row.isFlag == 0){
           return row.fileIndate + '至' + row.fileIndateEnd;
         } else if(row.isFlag == 1){
           return '永久';
         }
      }
      return cellValue;
    },
    cellStyle({row, column, rowIndex, columnIndex}){
      if(column.property === 'fileTypeKey' && row.required ){
        return 'background: #FEF0F0';
      }
    },

  },
  props:[ 'customerType'],
  data(){
    return{
      cmInfo: {},
      fileTableData: [],
      qualificatDocList: [],//资质文件
      moreFileData: [],
      isMore: false,
      editFileType: false,
      uploadType: '',

      colunms: [//表格列
        { prop: 'fileName', label: '文件名称', width: 100, fixed: false, tooltip: true},
        { prop: 'fileVersion', label: '版本',   width: 100, fixed: false,  tooltip: true },
        { prop: 'signMainPart', label: '签订主体',   width: 100, fixed: false,  tooltip: true },
        { prop: 'dealMainPartKey', label: '交易主体',   width: 100, fixed: false,  tooltip: true },
        { prop: 'signer', label: '签署人',   width: 100, fixed: false,  tooltip: true },
        { prop: 'fileIndate', label: '文件有效期',   width: 100, fixed: false,  tooltip: true },
        { prop: 'creater', label: '上传人',   width: 100, fixed: false,  tooltip: true },
        { prop: 'createTime', label: '上传时间',   width: 100, fixed: false,  tooltip: true },
        { prop: 'remark', label: '备注信息',   width: 100, fixed: false,  tooltip: true },
        { prop: 'status', label: '状态',   width: 100, fixed: false,  tooltip: true },
      ],
    }
  }
}
</script>

<style  scoped lang="scss">
.file-tips {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 0 0 15px;
}
</style>
