<template>
  <div class="app-container">
    <el-form
      :inline="true"
      ref="form"
      :model="form"
      :rules="rules"
      label-width="auto"
      style="margin-top: 20px"
      disabled
    >
      <el-divider content-position="left">基本信息</el-divider>
      <!-- <el-form-item label="融资产品编号" prop="zfpNumber">
          <el-input v-model="form.zfpNumber" placeholder="请输入融资产品编号" />
        </el-form-item> -->
      <el-row>
        <el-col :span="8">
          <el-form-item
            label="合同模板名称:"
            prop="zfcName"
          >
            <el-input
              v-model="form.zfcName"
              placeholder="请输入合同模板名称"
            /> </el-form-item
        ></el-col>
        <el-col :span="8"
          ><el-form-item
            label="合同类型:"
            prop="zfcType"
          >
            <el-select
              v-model="form.zfcType"
              placeholder="请选择合同类型"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item
            label="资金方:"
            prop="zfcManagementId"
          >
            <el-select
              style="width: 95%"
              v-model="form.zfcManagementId"
              placeholder="请选择资金方"
              clearable
              size="small"
            >
              <el-option
                v-for="(item, index) in companyList"
                :key="index"
                :label="item.scyName"
                :value="item.scyId"
              />
            </el-select> </el-form-item
        ></el-col>
      </el-row>
      <el-row>
        <el-form-item style="margin-left: 100px" >
          <el-table ref="tableContract" :data="nodeList" @selection-change="handleSelectionChange" style="width: 500px" >
            <el-table-column
              type="selection"
              width="50"
              align="center"/>
            <el-table-column label="签署节点" align="center" prop="zfcNode" :show-overflow-tooltip="true" > 
            </el-table-column>
            <el-table-column label="盖章关键字" align="center" prop="zfcSignKeyword" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.zfcSignKeyword"
                  size="small"
                  maxlength="200" 
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item
        >
        <!-- <el-col :span="8">
          <el-form-item
            label="签署主体:"
            prop="zfcSubject"
          >
            <el-select
              v-model="form.zfcSubject"
              placeholder="请选择签署主体"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in subjectOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item
            label="签署节点:"
            prop="zfcNode"
          >
            <el-select
              v-model="form.zfcNode"
              placeholder="请选择签署节点"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in nodeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select> </el-form-item
        ></el-col> -->
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item
            label="合同描述:"
            prop="zfcDesc"
            
          >
            <el-input
              type="textarea"
              maxlength="100"
              style="width:250%"
              show-word-limit
              v-model="form.zfcDesc"
              placeholder="请输入合同描述"
            /> </el-form-item
        ></el-col>
      </el-row>
     <!-- 合同模板文件 -->
      <el-divider content-position="left">合同模板文件</el-divider>
      <el-form-item label="合同模板文件" style="margin-left: 100px">
        <el-upload
          ref="upload"
          class="upload-demo"
          action=""
          :http-request="httpRequest"
          :before-remove="beforeRemove"
          :on-preview="handleFileDownload"
          accept=".doc,.docx"
          multiple
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :auto-upload="false"
          style="width:800px"
        >
          <!-- <el-button slot="trigger" size="small" type="primary"
            >点击选择</el-button
          >
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload"
            >上传到服务器</el-button
          > -->
        </el-upload>
      </el-form-item>

    </el-form>
    <!-- 保存 -->
    <div class="footer" style="margin-top: 100px; float: right">
      <el-button type="info" @click="cancel">取消</el-button>
      <!-- <el-button type="success" @click="submitForm">提交</el-button> -->
    </div>
  </div>
</template>

<script>
import { getContract,updateContract } from "@/api/service/contract/contract";
import { listCompany } from "@/api/common/company";
import { uploadFileNew } from "@/api/common/file";
import { getToken } from "@/utils/auth";
export default {
  name: "detailContract",
  components: {},
  data() {
    return {
      disabled: false,
      // 日期范围
      dateRange: [],
      //选中数据
      chooseList: [],
      // 选中数组
      ids: [],
      // 弹出层标题
      title: "",
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 资方列表
      companyList: [],
      //附件地址
      fileList:[],
      //数据字典
      typeOptions: [],
      subjectOptions: [],
      nodeOptions: [],
      nodeList:[],
      // 表单参数
      form: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      options: [],
      value: [],
      loading: false,
      // 表单校验
      rules: {
        zfcName: [
          {
            required: true,
            message: "合同模板名称",
            trigger: ["blur", "change"],
          },
        ],
        zfcManagementId: [
          {
            required: true,
            message: "资金方不能为空",
            trigger: ["blur", "change"],
          },
        ],
        zfcType: [
          {
            required: true,
            message: "合同类型",
            trigger: ["blur", "change"],
          },
        ],
        zfcSubject: [
          {
            required: true,
            message: "签署主体",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  created() {
    const zfcId = this.$route.params && this.$route.params.zfcId;
    this.reset();
    this.getCompanyList();
    //this.getList();
   this.getDicts("zc_zfc_type").then((response) => {
      this.typeOptions = response.data;
    });
    
    this.getDicts("zc_zfc_subject").then((response) => {
      this.subjectOptions = response.data;
    });
    getContract(zfcId).then((response) =>{
      this.form = response.data.zcFinanceContract;
      this.form.createTime = this.parseTime(new Date(response.data.zcFinanceContract.createTime),'{y}-{m}-{d} {h}:{m}:{s}');
      var zfcCode = this.form.zfcNode.split(",")
      var signKeyword = this.form.zfcSignKeyword.split(",")
      for(var i=0;i<zfcCode.length;i++){
        this.chooseList.push({zfcCode:zfcCode[i],zfcSignKeyword:signKeyword[i]});
      }
      this.getDicts("zc_zfc_node").then((response) => {
      this.nodeOptions = response.data;
        for(let i=0;i<this.nodeOptions.length;i++){
          var k = 0;
          for(let j=0;j<this.chooseList.length;j++){
            if(this.nodeOptions[i].dictValue == this.chooseList[j].zfcCode){
                this.nodeList.push({zfcNode:this.nodeOptions[i].dictLabel,zfcCode:this.nodeOptions[i].dictValue,zfcSignKeyword:this.chooseList[j].zfcSignKeyword})
                k =1;
            }
          }
          if(k != 1){
              this.nodeList.push({zfcNode:this.nodeOptions[i].dictLabel,zfcCode:this.nodeOptions[i].dictValue,zfcSignKeyword:''})
          } 
        }
      }).then(()=>{
        console.log(this.nodeList,"<=========")
        this.chooseList.forEach((item) => {
          this.nodeList.forEach((row) => {
            if (row.zfcCode == item.zfcCode) {
              this.$nextTick(() => {
                this.$refs.tableContract  &&
                  this.$refs.tableContract.toggleRowSelection(row, true);
                });
              }
            });
        });
      });
      this.userName = response.data.nickName;
      const pfiFileName = response.data.fileName;
      const fileUrl = response.data.fileUrl;
      const fileId = response.data.fileId;
      if (fileUrl && fileId && pfiFileName != null){
        this.fileList.push({name:pfiFileName, url: fileUrl, uid: fileId });
      }

      var state = this.form.zfpStatus;
      if(state == '01'){
        this.disabled = true ;
      }

      const type = "03";
      const zfcManagementId = this.form.zfcManagementId;
      listCompany(type,zfcManagementId).then(response =>{
        this.companyList = response.data;
      })
    });
    
  },
  activated() {
    this.reset();
    //this.getList();
  },
  methods: {
    /** 查询资方 */
    getCompanyList(){
      const type = "03";
      listCompany(type).then(response =>{
        this.companyList = response.data;
      })
    }, 
    reset(){
      this.form = {
      };
       this.resetForm("form");
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.go(-1);
      this.open = false;
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.chooseList = val;
    },
    /** 上传图片 */
    submitUpload() {
      this.$refs.upload.submit();
    },
    //文件移除提示
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${file.name}？`);
      for(let i = 0;i< this.fileList.length;i++){
        if(file.uid == this.fileList[i].uid){
          this.fileList.splice(i, 1);
          break;
        }
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    //手动上传文件触发
    httpRequest(param) {
      let fileObj = param.file; // 相当于input里取得的files
      let fd = new FormData(); // FormData 对象
      fd.append("file", fileObj); // 文件对象
      fd.append("fileType", "04"); // 类型：文件
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      uploadFileNew(fd).then((response) => {
        if (response) {
          this.fileList.push({name:response.fileName,uid : response.fileId,url:response.url+'/'+getToken()})
          this.msgSuccess("上传成功");
          loading.close();
        }
      }).catch((response) =>{
          if(!response){
            this.$message.warning(`上传失败`);
          }
          loading.close();
      });
    },
    /* 下载 */
    handleFileDownload(sfcFile){
        this.$confirm('是否确认下载'+sfcFile.name+'附件?', "警告", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: "warning"
        }).then(function() {
        if(sfcFile.name.substr(-3) == "pdf"){
          if(sfcFile.url.indexOf("getPdf") != -1){
            sfcFile.url = sfcFile.url.replace("getPdf","getBytes");
          }
          window.open(sfcFile.url+'/'+getToken());
        }else{
          var a = document.createElement('a');
          var event = new MouseEvent('click');
          a.download = sfcFile.name;
          a.href = sfcFile.url+'/'+getToken();
          a.dispatchEvent(event);
        }
        })
    },
    /** 保存按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        this.form.nodeList = this.chooseList;
        if(!this.fileList.length){
                this.$message({
                  message: '请上传附件！',
                  type: 'warning'
                });
                return;
              };
        console.log(this.form)
        this.form.zfcFile = this.fileList;
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          updateContract(this.form)
            .then((response) => {
              loading.close();
              this.msgSuccess("修改成功");
              this.$store.dispatch("tagsView/delView", this.$route);
              this.$router.go(-1);
            })
            .catch((response) => {
              loading.close();
            });
        }
      });
    },
    // submitData() {
    //   this.open = false;
    // },
    /* //  将数字金额转换为大写金额 */
  },
};
</script>
<style>
.single-select-table thead .el-table-column--selection .cell {
  display: none;
}

</style>
