<script setup>
import { contractInterface, sealInterence } from "@/api/api.js";
import { ElMessage } from "element-plus";
import { computed, nextTick, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

const route = useRoute()
const router = useRouter()

function ValidateUseCompanyName(rule, val, cb) {
  return pageState.sealForm.Use === "代付合同" && val === ""
    ? cb(new Error("请填写实际使用方"))
    : cb();
}

// 根据fileUrl判断文件类型
function fileType(fileUrl) {
  if (/^.+(\.pdf)$/i.test(fileUrl)) {
    return "pdf";
  } else if (/^.+(\.doc|\.docx)$/i.test(fileUrl)) {
    return "word";
  } else {
    return "other";
  }
}


// 用印id,有则表示编辑,无表示新增
const sealId = computed(() => {
  return route.query.id || null
})

// 判断上传控件是否显示
const isUploadShow = computed(() => {
  return pageState.sealForm.source === "系统合同"
})

const companySelector=ref(null)//搜索框实例

const sealForm = ref(null)//表单实例
const pageState = reactive({
  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是否触发
})

function init() {
  // 如果是编辑页面先获取用印详情信息
  if (sealId.value) {
    getsealApprovalDetail();
  }
}
init()


// 获取用印详情
async function getsealApprovalDetail() {
  try {
    const res = await sealInterence.sealApprovalDetail({
      SealId: sealId.value,
    });
    if (res.Ret === 200) {
      // 关闭监听
      pageState.isWatch = false;
      const SealDetail = res.Data.SealDetail;
      pageState.sealForm.Use = SealDetail.Use;
      pageState.sealForm.CreditCode = SealDetail.CreditCode;
      pageState.sealForm.ContractId = SealDetail.ContractId;
      pageState.sealForm.CompanyName = SealDetail.CompanyName;
      pageState.sealForm.FileNum = SealDetail.FileNum;
      // 返回数据改为多个文件url的数组 FileUrls
      // pageState.sealForm.fileList.push({ FileUrl: SealDetail.FileUrl });
      SealDetail.FileUrls.map(i => {
        pageState.sealForm.fileList.push({ FileUrl: i })
      })
      pageState.sealForm.Remark = SealDetail.Remark;
      pageState.sealForm.SealType = SealDetail.SealType.split(",");
      pageState.sealForm.ServiceType = SealDetail.ServiceType;
      pageState.sealForm.UseCompanyName = SealDetail.UseCompanyName;
      pageState.sealForm.source =
        SealDetail.ContractId > 0 ? "系统合同" : "上传附件";
      // 打开监听
      nextTick(() => {
        pageState.isWatch = true;
      })
    }
  } catch (err) {
    console.log(err);
  }
}
// 合同预览
function preview(file) {
  const fileTypeVal = fileType(file.FileUrl);
  let href = "";
  if (fileTypeVal === "word") {
    href =
      "https://view.officeapps.live.com/op/view.aspx?src=" + file.FileUrl;
  } else {
    href = file.FileUrl;
  }
  window.open(href, "_blank");
}
// 合同移除
function handleRemove(file) {
  pageState.sealForm.fileList = pageState.sealForm.fileList.filter(
    (item) => item.uid !== file.uid
  );
}
// 修改文件时触发  [选择了文件，上传成功，上传失败]
function changeFile(file, fileList) {
  pageState.sealForm.fileList = fileList.filter((item) => item.status==='success'&&item.FileUrl);
}
// 上传之前的钩子
function beforeUpload(file) {
  // 检查文件类型
  if (fileType(file.name) === "other") {
    ElMessage.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 function 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 = [];
      pageState.sealForm.fileList.push({ FileUrl: res.Data.ResourceUrl });
      console.log('1',pageState.sealForm.fileList);
      // 单独清除合同附件的校验
      sealForm.value.clearValidate("fileList");
      ElMessage.success("上传成功");
    }
  } catch (err) {
    console.log(err);
  }
}
// 关键字联想
async function querySearch(queryString, cb) {
  // 合同来源为上传附件时不进行联想
  if (pageState.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) pageState.sealForm.ContractId = 0;
  // 调用 callback 返回建议列表的数据
  cb(results);
}
// 选择事件
function selectHandel(item) {
  pageState.sealForm.CompanyName = item.CompanyName;
  pageState.sealForm.UseCompanyName =
    item.ContractBusinessType === "代付合同"
      ? item.UserCompanyName
      : item.CompanyName;
  pageState.sealForm.ContractId = item.ContractId;
  pageState.sealForm.ServiceType = item.ContractType;
  pageState.sealForm.CreditCode = item.CreditCode;
  pageState.sealForm.fileList = [];
  pageState.sealForm.fileList.push({ FileUrl: item.FileUrl });
  // 单独清除合同附件的校验
  sealForm.value.clearValidate("fileList");
}
// 表单提交
async function onSubmit() {
  try {
    await sealForm.value.validate();
    const formData = {
      CompanyName: pageState.sealForm.CompanyName,
      ContractId: pageState.sealForm.ContractId,
      CreditCode: pageState.sealForm.CreditCode,
      FileNum: pageState.sealForm.FileNum,
      FileUrls: pageState.sealForm.fileList.map(item => item.FileUrl),
      Remark: pageState.sealForm.Remark,
      SealType: pageState.sealForm.SealType.join(","),
      ServiceType: pageState.sealForm.ServiceType,
      Use: pageState.sealForm.Use,
      UseCompanyName: pageState.sealForm.UseCompanyName,
    };
    let res = {};
    if (sealId.value) {
      // 编辑用印
      formData.SealId = sealId.value * 1;
      res = await sealInterence.sealEditSealApproval(formData);
    } else {
      // 新增用印
      res = await sealInterence.sealApplySealApproval(formData);
    }
    // 成功
    if (res.Ret === 200) {
      ElMessage.success(res.Msg);
      router.go(-1);
    }
  } catch (err) {
    console.log(err);
  }
}
// 根据文件返回文件图标
function fileTypeIcon(file) {
  if (!file.FileUrl) return "";
  const fileTypeVal = fileType(file.FileUrl);
  return fileTypeVal === "word"
    ? require("@/assets/img/constract/word-icon.png")
    : require("@/assets/img/constract/pdf.png");
}


</script>

<template>
  <el-card class="update-seal-card">
    <el-form
      ref="sealForm"
      :model="pageState.sealForm"
      :rules="pageState.sealRules"
      label-width="140px"
    >
      <div class="one-part">
        <div class="box">
          <el-form-item label="用印用途：" prop="Use">
            <el-select v-model.trim="pageState.sealForm.Use" clearable>
              <el-option
                v-for="item in pageState.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="companySelector.suggestions = []"
              v-model.trim="pageState.sealForm.CompanyName"
            >
              <template #default="{ 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="pageState.sealForm.ServiceType"
              :disabled="pageState.sealForm.source === '系统合同'"
              clearable
            >
              <el-option
                v-for="item in pageState.ServiceTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :class="{ required: pageState.sealForm.Use === '代付合同' }"
            label="实际使用方："
            prop="UseCompanyName"
            ><el-input
              class="form-input"
              placeholder="请填写实际使用方名称"
              v-model.trim="pageState.sealForm.UseCompanyName"
              :disabled="pageState.sealForm.source === '系统合同'"
            ></el-input
          ></el-form-item>
          <el-form-item label="加盖何种印章：" prop="SealType">
            <el-select v-model="pageState.sealForm.SealType" multiple clearable>
              <el-option
                v-for="item in pageState.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="pageState.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="pageState.sealForm.CreditCode"
              :disabled="pageState.sealForm.source === '系统合同'"
            ></el-input
          ></el-form-item>
          <el-form-item label="文件份数：" prop="FileNum"
            ><el-input-number
              :min="1"
              v-model="pageState.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="pageState.sealForm.Remark"
          ></el-input
        ></el-form-item>
        <el-form-item label="合同附件：" prop="fileList">
          <!-- 需求更改 可上传多个附件 crm_8.7 -->
          <el-upload
            list-type="picture-card"
            :file-list="pageState.sealForm.fileList"
            action="#"
            multiple
            :class="{ disabled: isUploadShow }"
            :on-change="changeFile"
            :before-upload="beforeUpload"
            :http-request="upload"
            :disabled="pageState.sealForm.source === '系统合同'"
            accept=".pdf,.doc,.docx"
          >
            <i class="el-icon-plus" />
            <template #file="{ file }">
              <div>
                <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="pageState.sealForm.source !== '系统合同'"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </template>
          </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>

<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>