<template>
  <el-card class="update-seal-card">
    <el-form
      ref="sealForm"
      :model="sealForm"
      :rules="sealRules"
      label-width="120px"
    >
      <div class="one-part">
        <div class="box">
          <el-form-item label="用印用途：" prop="Use">
            <el-select v-model.trim="sealForm.Use" clearable>
              <el-option
                v-for="item in purposeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户名称：" prop="CompanyName">
            <el-autocomplete
              ref="companySelector"
              popper-class="custom-autocomplete"
              placeholder="请输入用户名称"
              :fetch-suggestions="querySearch"
              :trigger-on-focus="false"
              @select="selectHandel"
              @focus="$refs.companySelector.suggestions = []"
              v-model.trim="sealForm.CompanyName"
            >
              <template slot-scope="{ item }">
                <h5 class="name">{{ item.CompanyName }}</h5>
                <p class="item">合同编号:{{ item.ContractCode }}</p>
                <p class="item">合同类型:{{ item.ContractType }}</p>
                <p class="item">合同金额:{{ item.Price }}</p>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="合同类型：" prop="ServiceType">
            <el-select
              v-model="sealForm.ServiceType"
              :disabled="sealForm.source === '系统合同'"
              clearable
            >
              <el-option
                v-for="item in ServiceTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :class="{ required: sealForm.Use === '代付合同' }"
            label="实际使用方："
            prop="UseCompanyName"
            ><el-input
              class="form-input"
              placeholder="请填写实际使用方名称"
              v-model.trim="sealForm.UseCompanyName"
              :disabled="sealForm.source === '系统合同'"
            ></el-input
          ></el-form-item>
          <el-form-item label="加盖何种印章：" prop="SealType">
            <el-select v-model="sealForm.SealType" multiple clearable>
              <el-option
                v-for="item in SealTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="box">
          <el-form-item label="合同来源：" prop="source">
            <el-radio-group v-model="sealForm.source">
              <el-radio label="系统合同" border>系统合同</el-radio>
              <el-radio label="上传附件" border>上传附件</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="社会信用码：" prop="CreditCode"
            ><el-input
              class="form-input"
              placeholder="请填写统一社会信用码"
              v-model.trim="sealForm.CreditCode"
              :disabled="sealForm.source === '系统合同'"
            ></el-input
          ></el-form-item>
          <el-form-item label="文件份数：" prop="FileNum"
            ><el-input-number
              :min="1"
              v-model="sealForm.FileNum"
            ></el-input-number
          ></el-form-item>
        </div>
      </div>
      <div class="two-part">
        <el-form-item label="审批备注：" prop="Remark"
          ><el-input
            placeholder="请填写备注"
            v-model="sealForm.Remark"
          ></el-input
        ></el-form-item>
        <el-form-item label="合同附件：" prop="fileList">
          <!-- 需求更改 可上传多个附件 crm_8.7 -->
          <el-upload
            list-type="picture-card"
            :file-list="sealForm.fileList"
            action="#"
            multiple
            :class="{ disabled: isUploadShow }"
            :on-change="changeFile"
            :before-upload="beforeUpload"
            :http-request="upload"
            :disabled="sealForm.source === '系统合同'"
            accept=".pdf,.doc,.docx"
          >
            <i class="el-icon-plus" />
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="fileTypeIcon(file)"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="preview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="sealForm.source !== '系统合同'"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
      </div>
      <div class="btn-group">
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </div>
    </el-form>
  </el-card>
</template>

<script>
import { contractInterface, sealInterence } from "@/api/api.js";
export default {
  name: "UpdateSeal",
  data() {
    // 实际使用方校验规则
    const ValidateUseCompanyName = (rule, val, cb) => {
      return this.sealForm.Use === "代付合同" && val === ""
        ? cb(new Error("请填写实际使用方"))
        : cb();
    };
    return {
      sealForm: {
        //表单数据
        Use: "", //用印用途
        CompanyName: "", //客户名称
        ServiceType: "", //合同类型
        UseCompanyName: "", //实际使用方
        SealType: [], //加盖何种印章
        source: "系统合同", //合同来源
        CreditCode: "", //社会信用码
        FileNum: 1, //文件份数
        Remark: "", //审批备注
        fileList: [], //合同附件
        ContractId: 0, //合同id(默认为0)
      },
      sealRules: {
        //表单校验规则
        Use: [{ required: true, message: "请选择用印用途", trigger: "blur" }],
        CompanyName: [
          { required: true, message: "请选择客户名称", trigger: "blur" },
        ],
        ServiceType: [
          { required: true, message: "请选择合同类型", trigger: "change" },
        ],
        UseCompanyName: [
          { validator: ValidateUseCompanyName, trigger: "change" },
        ],
        SealType: [
          { required: true, message: "请选择加盖何种印章", trigger: "blur" },
        ],
        CreditCode: [
          { required: true, message: "请填写社会信用码", trigger: "change" },
        ],
        fileList: [
          { required: true, message: "请上传合同附件", trigger: "change" },
        ],
      },
      purposeOptions: [
        //用印用途选项
        { label: "销售合同", value: 1 },
        { label: "代付合同", value: 2 },
        { label: "渠道合同", value: 3 },
        { label: "付款通知函", value: 4 },
        { label: "招投标", value: 5 },
        { label: "战略合作协议", value: 6 },
        { label: "总对总协议", value: 7 },
      ],
      ServiceTypeOptions: [
        //合同类型选项
        { label: "新签合同", value: 1 },
        { label: "续约合同", value: 2 },
        { label: "补充协议", value: 3 },
        { label: "代付合同", value: 4 },
      ],
      SealTypeOptions: [
        //加盖何种印章选项
        { label: "合同章", value: 1 },
        { label: "公章", value: 2 },
        { label: "法人章", value: 3 },
      ],
      isWatch: true, // 控制watch是否触发
    };
  },
  created() {
    // 如果是编辑页面先获取用印详情信息
    if (this.sealId) {
      this.getsealApprovalDetail();
    }
  },
  computed: {
    // 用印id,有则表示编辑,无表示新增
    sealId() {
      return this.$route.query.id || null;
    },
    // 判断上传控件是否显示
    isUploadShow() {
      return (
        // this.sealForm.fileList.length === 1 ||
        this.sealForm.source === "系统合同"
      );
    },
  },
  methods: {
    // 获取用印详情
    async getsealApprovalDetail() {
      try {
        const res = await sealInterence.sealApprovalDetail({
          SealId: this.sealId,
        });
        if (res.Ret === 200) {
          // 关闭监听
          this.isWatch = false;
          const SealDetail = res.Data.SealDetail;
          this.sealForm.Use = SealDetail.Use;
          this.sealForm.CreditCode = SealDetail.CreditCode;
          this.sealForm.ContractId = SealDetail.ContractId;
          this.sealForm.CompanyName = SealDetail.CompanyName;
          this.sealForm.FileNum = SealDetail.FileNum;
          // 返回数据改为多个文件url的数组 FileUrls
          // this.sealForm.fileList.push({ FileUrl: SealDetail.FileUrl });
          SealDetail.FileUrls.map(i =>{
            this.sealForm.fileList.push({FileUrl:i})
          })
          this.sealForm.Remark = SealDetail.Remark;
          this.sealForm.SealType = SealDetail.SealType.split(",");
          this.sealForm.ServiceType = SealDetail.ServiceType;
          this.sealForm.UseCompanyName = SealDetail.UseCompanyName;
          this.sealForm.source =
            SealDetail.ContractId > 0 ? "系统合同" : "上传附件";
          // 打开监听
          this.$nextTick(() => {
            this.isWatch = true;
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 合同预览
    preview(file) {
      const fileType = this.fileType(file.FileUrl);
      let href = "";
      if (fileType === "word") {
        href =
          "https://view.officeapps.live.com/op/view.aspx?src=" + file.FileUrl;
      } else {
        href = file.FileUrl;
      }
      window.open(href, "_blank");
    },
    // 合同移除
    handleRemove(file) {
      this.sealForm.fileList = this.sealForm.fileList.filter(
        (item) => item.uid !== file.uid
      );
    },
    // 修改文件时触发  [选择了文件，上传成功，上传失败]
    changeFile(file, fileList) {
      this.fileList = fileList.map((item) => item);
    },
    // 上传之前的钩子
    beforeUpload(file) {
      // 检查文件类型
      if (this.fileType(file.name) === "other") {
        this.$message.error("上传文件只能是 PDF、DOC、DOCX 格式!");
        return false;
      }
      //  检查大小
      //   const maxSize = 10 * 1024 * 1024
      //   if (maxSize < file.size) {
      //     this.$message.error('图片大小最大不能超过5M')
      //     return false
      //   }
      return true; // 最后一定要return  true
    },
    // 上传事件
    async upload(params) {
      if (!params.file) return;
      const fd = new FormData();
      fd.append("file", params.file);
      try {
        const res = await sealInterence.resourceUpload(fd);
        if (res.Ret === 200) {
          // this.sealForm.fileList = [];
          this.sealForm.fileList.push({ FileUrl: res.Data.ResourceUrl });
          // 单独清除合同附件的校验
          this.$refs.sealForm.clearValidate("fileList");
          this.$message.success("上传成功");
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 关键字联想
    async querySearch(queryString, cb) {
      // 合同来源为上传附件时不进行联想
      if (this.sealForm.source === "上传附件" || queryString === "")
        return cb([]);
      let results = [];
      try {
        const res = await sealInterence.getContractListBySeal({
          Keyword: queryString,
        });
        if (res.Ret === 200) {
          results = res.Data;
        }
      } catch (err) {
        console.log(err);
      }
      if (!results.length) this.sealForm.ContractId = 0;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    // 选择事件
    selectHandel(item) {
      this.sealForm.CompanyName = item.CompanyName;
      this.sealForm.UseCompanyName =
        item.ContractBusinessType === "代付合同"
          ? item.UserCompanyName
          : item.CompanyName;
      this.sealForm.ContractId = item.ContractId;
      this.sealForm.ServiceType = item.ContractType;
      this.sealForm.CreditCode = item.CreditCode;
      this.sealForm.fileList = [];
      this.sealForm.fileList.push({ FileUrl: item.FileUrl });
      // 单独清除合同附件的校验
      this.$refs.sealForm.clearValidate("fileList");
    },
    // 表单提交
    async onSubmit() {
      try {
        await this.$refs.sealForm.validate();
        const formData = {
          CompanyName: this.sealForm.CompanyName,
          ContractId: this.sealForm.ContractId,
          CreditCode: this.sealForm.CreditCode,
          FileNum: this.sealForm.FileNum,
          FileUrls: this.sealForm.fileList.map(item => item.FileUrl),
          Remark: this.sealForm.Remark,
          SealType: this.sealForm.SealType.join(","),
          ServiceType: this.sealForm.ServiceType,
          Use: this.sealForm.Use,
          UseCompanyName: this.sealForm.UseCompanyName,
        };
        let res = {};
        if (this.sealId) {
          // 编辑用印
          formData.SealId = this.sealId * 1;
          res = await sealInterence.sealEditSealApproval(formData);
        } else {
          // 新增用印
          res = await sealInterence.sealApplySealApproval(formData);
        }
        // 成功
        if (res.Ret === 200) {
          this.$message.success(res.Msg);
          this.$router.go(-1);
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 根据文件返回文件图标
    fileTypeIcon(file) {
      if (!file.FileUrl) return "";
      const fileType = this.fileType(file.FileUrl);
      return fileType === "word"
        ? require("@/assets/img/constract/word-icon.png")
        : require("@/assets/img/constract/pdf.png");
    },
    // 根据fileUrl判断文件类型
    fileType(fileUrl) {
      if (/^.+(\.pdf)$/i.test(fileUrl)) {
        return "pdf";
      } else if (/^.+(\.doc|\.docx)$/i.test(fileUrl)) {
        return "word";
      } else {
        return "other";
      }
    },
  },
  watch: {
    // 切换合同来源时清空表单
    "sealForm.source"(val) {
      if (!this.isWatch) return;
      this.sealForm = {
        Use: "", //用印用途
        CompanyName: "", //客户名称
        ServiceType: "", //合同类型
        UseCompanyName: "", //实际使用方
        SealType: [], //加盖何种印章
        source: val, //合同来源
        CreditCode: "", //社会信用码
        FileNum: 1, //文件份数
        Remark: "", //审批备注
        fileList: [], //合同附件
        ContractId: 0, //合同id(默认为0)
      };
      // 清除校验提示
      this.$nextTick(() => {
        this.$refs.sealForm.clearValidate();
      });
    },
  },
};
</script>

<style lang='scss'>
.update-seal-card {
  .one-part {
    display: flex;
    .box {
      flex: 1;
    }
    .el-select,
    .el-autocomplete,
    .form-input {
      width: 300px;
    }
    .el-input-number {
      width: 120px;
      .el-input .el-input__inner {
        pointer-events: none;
      }
    }
    .required .el-form-item__label {
      &::before {
        content: "*";
        color: #f56c6c;
        margin-right: 4px;
      }
    }
  }
  .two-part {
    .disabled .el-upload--picture-card {
      visibility: hidden;
    }
    .el-upload-list {
      // position: absolute;
      .el-upload-list__item {
        border: 0;
      }
    }
  }
  .btn-group {
    display: flex;
    justify-content: center;
  }
}
.custom-autocomplete {
  .item {
    line-height: 20px;
  }
}
</style>