<script setup>
import { ref,reactive,nextTick } from "vue";
import {ElMessage,ElMessageBox} from "element-plus"
import { useRouter} from 'vue-router';
import _ from 'lodash'
import { InfoFilled } from '@element-plus/icons-vue'

import { contractInterface } from "@/api/api.js";
import{province_sorce,city_sorce} from '@/utils/distpicker';
import QyServiceTable from "./components/QyServiceTable.vue"; //权益服务内容表格组件
import FiccServiceTable from "./components/FiccServiceTable.vue"; //ficc服务内容表格组件
import { CalculationDate } from "@/utils/CalculationDate";
import {formatTime} from '@/hooks/mixins/index.js'

const $router = useRouter()

const province_sorce_value=province_sorce
const city_sorce_value=city_sorce

const RoleType=ref(localStorage.getItem("Role") || "")
const formData=reactive({
  CompanyName: "",
  CreditCode: "",
  Province: "",
  City: "",
  Address: "",
  Fax: "",
  Phone: "",
  Postcode: "",
  OriginalPrice: "",
  trueUseName: "",
  sellerRemark: "",
  PayRemark: "",
  RelationContractId: null,
})

const formRule={
  CompanyName: [{ required: true, message: "请填写名称", trigger: "blur" }],
  CreditCode: [{ required: true, message: "请填写信用码", trigger: "blur" }],
  Province: [{ required: true, message: "请选择地址", trigger: "change" }],
  OriginalPrice: [
    { required: true, message: "请填写代付金额", trigger: "blur" },
    // { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: "请输入正确的格式,可保留两位小数" },
  ],
  trueUseName: [{ required: true, message: "请输入关键字", trigger: "change" }],
  PayRemark: [{ required: true, message: "请填写付款方式说明", trigger: "blur" }],
  Address: [{ required: true, message: "请填写详细地址", trigger: "blur" }],
  Phone: [{ required: true, message: "请填写电话", trigger: "blur" }],
}

const searchList=ref([])
const contractList=ref([])
const showContractList=ref(false)
const relationContractData=ref(null) //选择的关联合同数据
const ficcServiceData=ref(null) //ficc 底部表格数据
const qyServiceData=ref(null) //权益底部表格数据
const serviceShow=ref(false) //是否显示查看报价单
const serviceCon=ref({}) //选择的服务项 查看报价单/选择品种
// filters

const formatPrice=(str)=>{
  if(!str) return ''
  str=str.toString()
  let num1='',num2=''
  if(str.indexOf(".")!=-1){
    num1=str.substring(0,str.indexOf("."))
    num2=str.substring(str.length,str.indexOf("."))
    if(Number(num2)<=0){
      num2=''
    }
  }else{
    num1=str
  }
  return num1.replace(/(?!^)(?=(\d{3})+$)/g, ',')+num2
}
// 金额转中文大写
const digitUppercase=(n)=>{
  if(!n) return ''
  n=n.toString().replace(/,/g,'')
  let fraction = ["角", "分"];
  let digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  let unit = [
    ["元", "万", "亿"],
    ["", "拾", "佰", "仟"],
  ];
  let head = n < 0 ? "欠" : "";
  n = Math.abs(n);
  let s = "";
  for (let i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, "");
  }
  // s = s || "整";

  n = Math.floor(n);
  for (let i = 0; i < unit[0].length && n > 0; i++) {
    let p = "";
    for (let j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p;
      n = Math.floor(n / 10);
    }
    s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;
  }
  return (
    "大写：" + (head + s.replace(/(零.)*零元/, "元").replace(/(零.)+/g, "零"))
    // .replace(/^整$/, "零元整")
  );
}
//计算多少年
const formateYear=(e)=>{
  if (e[0]) {
    return `有效期为${CalculationDate(e[0], e[1])}`;
  } else {
    return "";
  }
}

// 搜索出客户
const customeSearch=async(query)=>{
  if (!query) return;
  const res = await contractInterface.getBusinessContractCompanyNameList({ Keyword: query });
  if (res.Ret === 200) {
    searchList.value = res.Data;
  }
}
// 选择客户并搜索出其下已签回合同
const handleSelectTrueUseName=(e)=>{
  nextTick(async()=>{
    if(isBlurManual.value){
      isBlurManual.value=false
      return 
    }
    if (e||!formData.trueUseName) return;

    const res = await contractInterface.getBusinessContractList({ CompanyName: formData.trueUseName });
    if (res.Ret === 200) {
      showContractList.value = true;
      nextTick(() => {
        contractList.value = res.Data.List;
      });
    }
  })

}

// 确认关联
const handleRelation=async()=>{
  if (!formData.RelationContractId) {
    ElMessage.warning("请选择一份合同进行关联");
    return;
  }
  const res = await contractInterface.getContractDetail({ ContractId: formData.RelationContractId });
  if (res.Ret === 200) {
    relationContractData.value = res.Data;
    getServiceList();
    showContractList.value = false;
  }
}

const trueUseNameRef=ref(null)
const isBlurManual=ref(false)
const closeTrueUseNameDia=()=>{
  // element-plus 会在弹窗关闭后，返回焦点给el-select组件……
  console.log('失去焦点');
  isBlurManual.value=true
  trueUseNameRef.value.blur()
}

//获取服务套餐模板数据
const getServiceList=()=>{
  contractInterface.getServiceList({ ProductId: relationContractData.value.ProductId }).then((res) => {
    if (res.Ret === 200) {
      if (relationContractData.value.ProductId === 1) {
        ficcServiceData.value = res.Data;
      } else {
        qyServiceData.value = res.Data;
      }
    }
  });
}

//显示查看报价单弹窗
const handleShowService=(e)=>{
  // 小套餐情况处理表格数据
  if (e.Detail) {
    let temarr = e.Detail.map((rowItem) => {
      let rowArr = [];
      for (let key in rowItem) {
        if (key.substring(0, 3) === "Col" && rowItem[key] !== "") {
          rowArr.push(JSON.parse(rowItem[key]));
        }
      }
      return rowArr;
    });
    serviceCon.value = { ...e, tableHeadData: temarr[0], tableData: temarr.slice(1) };
  } else {
    serviceCon.value = e;
  }
  serviceShow.value = true;
}

//选地地区时 选则的省份改变重置city为空
const provinceChange=(e)=>{
  formData.Province =e.value=='省'?'':e.value;
  formData.City=''
}

//选择地区
const selectRegion=(e)=>{
  formData.Province =e.province.value=='省'?'':e.province.value;
  formData.City = e.city.value=='市'?'':e.city.value;
}

const formRef=ref(null)
// 提交
const handleSubmit=(type)=>{
  formRef.value.validate(async (valid) => {
    if (valid) {
      let params = {
        ContractType:"新签合同",
        ContractBusinessType:"代付合同",
        Address: formData.Address,
        City: formData.City,
        CompanyName: formData.CompanyName,
        CreditCode: formData.CreditCode,
        Province: formData.Province,
        Fax: formData.Fax,
        Phone: formData.Phone,
        Postcode: formData.Postcode,
        OriginalPrice: Number(formData.OriginalPrice.replace(/,/g,'')),
        sellerRemark: formData.sellerRemark,
        PayRemark: formData.PayRemark,
        TemplateId: RoleType.value === "ficc_seller" ? 1 : 2,
        RelationContractId: formData.RelationContractId,
      };
      if(!params.City){
        ElMessage.warning("请选择城市")
        return
      }
      if(!params.RelationContractId){
        ElMessage.warning('请选择关联合同')
        return
      }
      if (type === "预览") {
        params = { ...params, IsAudit: false };
        handlePreview(params);
        return;
      } else if (type === "存草稿") {
        params = { ...params, IsAudit: false };
      } else {
        params = { ...params, IsAudit: true };
      }
      const res = await contractInterface.addContract(params);
      if (res.Ret === 200) {
        $router.go(-1);
      }
    }else{
      ElMessage.warning('请完善必填项')
    }
  });
}
//前去预览
const handlePreview=(params)=>{
  contractInterface.previewContract(params).then((res) => {
    if (res.Ret === 200) {
      sessionStorage.setItem("contractdtl", res.Data.Html);
      let { href } = $router.resolve({ path: "/contractdtl" });
      window.open(href, "_blank");
    }
  });
}

// 金额输入框获取焦点
const handlePriceBoxFocus=(key)=>{
  let val=formData[key]
  val=val.replace(/,/g,'')
  formData[key]=val
}
// 金额输入框获失去焦点
const handlePriceBoxBlur=(key)=>{
  let str=formData[key]
  let num1='',num2=''
  if(str.indexOf(".")!=-1){
    num1=str.substring(0,str.indexOf("."))
    num2=str.substring(str.length,str.indexOf("."))
    if(Number(num2)<=0){
      num2=''
    }
  }else{
    num1=str
  }
  formData[key]=num1.replace(/(?!^)(?=(\d{3})+$)/g, ',')+num2
}

</script>

<template>
  <div class="addcontractdc-container">
    <el-form ref="formRef" :model="formData" label-position="left" :rules="formRule" label-width="110px" size="large">
      <section class="section">
        <h2 class="section-title">客户信息</h2>
        <div class="section-container">
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="代付方" prop="CompanyName" style="width: 50%">
              <el-input v-model="formData.CompanyName" placeholder="请输入名称" style="width: 350px"></el-input>
            </el-form-item>
            <el-form-item label="社会信用码" prop="CreditCode" style="width: 50%">
              <el-input v-model="formData.CreditCode" placeholder="请输入社会信用码" style="width: 350px"></el-input>
            </el-form-item>
          </div>
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="公司地址" prop="Province" style="width: 50%">
              <v-distpicker :province-source="province_sorce_value"
                :city-source="city_sorce_value"  :province="formData.Province" :city="formData.City" hide-area @province="provinceChange" @selected="selectRegion"></v-distpicker>
            </el-form-item>
            <el-form-item label="详细地址" prop="Address" style="width: 50%">
              <el-input v-model="formData.Address" placeholder="请输入详细地址" style="width: 350px"></el-input>
            </el-form-item>
          </div>
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="传真" prop="Fax" style="width: 50%">
              <el-input v-model="formData.Fax" placeholder="请输入传真" style="width: 350px"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="Phone" style="width: 50%">
              <el-input v-model="formData.Phone" placeholder="请输入电话" style="width: 350px"></el-input>
            </el-form-item>
          </div>
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="邮编" prop="Postcode" style="width: 50%">
              <el-input v-model="formData.Postcode" placeholder="请输入邮编" style="width: 350px"></el-input>
            </el-form-item>
            <el-form-item label="代付金额" prop="OriginalPrice" style="width: 50%">
              <el-input v-model="formData.OriginalPrice" @focus="handlePriceBoxFocus('OriginalPrice')" @blur="handlePriceBoxBlur('OriginalPrice')" placeholder="请输入金额" style="width: 350px"></el-input>
              <span style="line-height: 40px;margin-left:20px">{{ digitUppercase(formData.OriginalPrice)  }}</span>
            </el-form-item>
          </div>
        </div>
      </section>
      <section class="section">
        <el-form-item label="付款方式说明" prop="PayRemark">
          <el-input type="textarea" v-model="formData.PayRemark" placeholder="请输入付款方式说明（请参考以下说明模板填写，请勿填写现金/转账等支付形式）" style="width: 80%"></el-input>
          <p>说明模板：甲方自合同生效日起的十日之内一次性支付一年服务费，乙方收款后为甲方开具合法有效的增值税发票。</p>
        </el-form-item>
        <el-form-item label="实际使用方" prop="trueUseName" class="border-top">
          <el-select v-model="formData.trueUseName" filterable remote placeholder="关键词搜索" ref="trueUseNameRef"
          :remote-method="customeSearch" @visible-change="handleSelectTrueUseName" style="width: 500px">
            <el-option v-for="item in searchList" :key="item" :label="item" :value="item"> </el-option>
          </el-select>
        </el-form-item>
      </section>

      <section class="section" v-if="relationContractData">
        <h2 class="section-title">合同信息</h2>
        <div class="section-container">
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="合同编号" style="width: 50%">
              <span>{{ relationContractData.ContractCode }}</span>
            </el-form-item>
            <el-form-item label="合同归属" style="width: 50%">
              <span>{{ relationContractData.ProductId === 1 ? "ficc" : "权益" }}</span>
            </el-form-item>
          </div>
          <el-form-item label="合同类型" class="border-top">
            <el-radio-group v-model="relationContractData.ContractType">
              <div style="display: flex">
                <div style="margin-right: 10px">
                  <el-radio label="新签合同" disabled>新签合同</el-radio>
                  <el-tooltip effect="dark" style="cursor: pointer;width:20px;">
                    <template #content>没有正式转试用记录的客户，在申请转正时提交的合同</template>
                    <el-icon :size="16" style="margin-left:-20px"><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
                <div style="margin-right: 10px">
                  <el-radio label="续约合同" disabled>续约合同</el-radio>
                  <el-tooltip effect="dark" style="cursor: pointer;width:20px;">
                    <template #content>
                      1、有正式转试用记录的客户，在申请转正时提交的合同<br>
										  2、所有客户在续约申请时提交的合同
                    </template>
                    <el-icon :size="16" style="margin-left:-20px"><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
                <div style="margin-right: 10px" v-if="RoleType !== 'rai_seller'">
                  <el-radio label="补充协议" disabled>补充协议</el-radio>
                </div>
              </div>
            </el-radio-group>
          </el-form-item>
          <div class="flex border-top" v-if="relationContractData.timeRange">
            <el-form-item label="合同期限" style="width: 50%">
              <el-date-picker disabled v-model="relationContractData.timeRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
            </el-form-item>
            <span style="line-height: 40px">{{ formateYear(relationContractData.timeRange) }}</span>
          </div>

          <div class="flex border-top">
            <el-form-item label="合同金额" style="width: 50%">
              <el-input disabled :value="formatPrice(relationContractData.OriginalPrice)" placeholder="请输入合同金额" style="width: 220px"></el-input>
            </el-form-item>
            <span style="line-height: 40px">{{ digitUppercase(relationContractData.OriginalPrice)  }}</span>
          </div>

          <div class="flex border-top">
            <el-form-item label="优惠后金额" style="width: 50%">
              <el-input disabled :value="formatPrice(relationContractData.Price)" placeholder="请输入优惠后金额" style="width: 220px"></el-input>
            </el-form-item>
            <span style="line-height: 40px">{{ digitUppercase(relationContractData.Price)  }}</span>
          </div>

          <el-form-item label="付款方式说明" class="border-top">
            <el-input
              type="textarea"
              disabled
              v-model="relationContractData.PayRemark"
              placeholder="请输入付款方式说明（请参考以下说明模板填写，请勿填写现金/转账等支付形式）"
              style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="付款方" class="border-top">
            <el-input
              type="textarea"
              disabled
              v-model="relationContractData.PayChannel"
              placeholder="代付，请填写代付的券商名称或期货公司名称；非代付，请填写无。（请勿填写现金/转账等支付形式）"
              style="width: 80%"
            ></el-input>
          </el-form-item>
        </div>
      </section>

      <section class="section" v-if="relationContractData">
        <h2 class="section-title">服务内容</h2>
          <div class="section-container">
            <!-- ficc 服务内容表格 -->
            <FiccServiceTable
              :canEdit="false"
              :serviceData="ficcServiceData"
              :hasSercive="relationContractData.Service"
              @handleShowService="handleShowService"
              v-if="relationContractData.ProductId === 1 && ficcServiceData"
            ></FiccServiceTable>

            <!-- 权益 服务内容表格 -->
            <QyServiceTable
              :canEdit="false"
              :serviceData="qyServiceData"
              :hasSercive="relationContractData.Service"
              @handleShowService="handleShowService"
              v-if="relationContractData.ProductId === 2 && qyServiceData"
            ></QyServiceTable>
          </div>
          <p style="margin-top: 30px; margin-bottom: 20px">补充内容（eg额外赠送、路演次数规定）</p>
          <el-radio :model-value="relationContractData.Remark?'1':'2'" label="2" disabled>无</el-radio>
          <el-radio :model-value="relationContractData.Remark?'1':'2'" label="1" disabled>有</el-radio>
          <el-input v-if="relationContractData.Remark" disabled type="textarea" v-model="relationContractData.Remark" rows="5" placeholder="请输入内容" style="margin: 20px 0; display: block; box-sizing: border-box"></el-input>
      </section>

      <section class="section">
        <h2 class="section-title">审批备注</h2>
        <div class="section-container">
          <el-form-item label="备注" prop="sellerRemark" class="border-top">
            <el-input type="textarea" v-model="formData.sellerRemark" placeholder="请输入备注（仅供审批人查看，不在生成合同中展示）" style="width: 80%"></el-input>
          </el-form-item>
        </div>
        <div style="text-align: center; margin-top: 40px; margin-bottom: 20px">
          <el-button type="primary" plain style="width: 145px" @click="handleSubmit('预览')" size="large">预览</el-button>
          <el-button type="primary" @click="handleSubmit('存草稿')" style="width: 145px" size="large">存草稿</el-button>
          <el-button type="primary" @click="handleSubmit('提交')" style="width: 145px" size="large">提交</el-button>
        </div>
      </section>
    </el-form>

    <!-- 选择合同弹窗 -->
    <el-dialog v-dialogDrag :title="`搜索到${formData.trueUseName}下合同`" :append-to-body="true" 
    v-model="showContractList" width="50%" center @close="closeTrueUseNameDia" draggable>
      <el-table :data="contractList" border height="60vh">
        <el-table-column align="center" width="50">
          <template #default="scope">
            <el-radio v-model="formData.RelationContractId" :label="scope.row.ContractId"><span></span></el-radio>
          </template>
        </el-table-column>
        <el-table-column label="合同编号" prop="ContractCode" align="center"></el-table-column>
        <el-table-column label="销售" prop="SellerName" align="center" width="80"></el-table-column>
        <el-table-column label="合同类型" prop="ContractType" align="center" width="80"></el-table-column>
        <el-table-column label="合同有效期" prop="ContractType" align="center" width="180">
          <template #default="scope">{{ formatTime(scope.row.StartDateStr)  }}~{{ formatTime(scope.row.EndDateStr) }}</template>
        </el-table-column>
        <el-table-column key="合同金额" align="center" prop="Price" label="合同金额" width="100"></el-table-column>
        <el-table-column key="合同状态" align="center" prop="Status" label="合同状态" width="80"></el-table-column>
        <el-table-column key="签回时间" align="center" prop="Status" label="签回时间" width="160">
          <template #default="scope">{{ formatTime(scope.row.CheckBackFileTimeStr) }}</template>
        </el-table-column>
      </el-table>
      <div style="text-align: center; margin: 30px 0">
        <el-button type="primary" @click="handleRelation" size="large">确定关联</el-button>
        <el-button type="primary" plain @click="showContractList = false" size="large">取消</el-button>
      </div>
    </el-dialog>

    <!-- 查看报价单弹窗 -->
    <el-dialog v-dialogDrag v-model="serviceShow" width="60%" class="self-dialog-c" :modal-append-to-body="false" @close="serviceShow=false" :show-close="false">
      <h2 class="title" style="text-align: center; color: #000">{{RoleType == 'ficc_seller'? serviceCon.Title : serviceCon.showTitle}}</h2>
      <img class="img" style="width: 100%; display: block; margin: 20px auto" 
      :src="RoleType == 'ficc_seller'? serviceCon.Value : serviceCon.showValue" />
      <div style="text-align: center; margin-bottom: 30px">
        <el-button type="primary" @click="serviceShow=false" size="large">知道了</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.addcontractdc-container .self-dialog-c .el-dialog__header {
  background-color: #fff;
  padding: 0;
}
.addcontractdc-container .self-dialog-c {
  width: auto;
  max-width: 60%;
}
</style>
<style lang="scss" scoped>
.addcontractdc-container {
  min-height: calc(100vh - 250px);
  position: relative;
  font-size: 16px;
  color: #000;
}
.flex {
  display: flex;
}
.section {
  background-color: #fff;
  border: 1px solid #aab4cc;
  border-radius: 4px;
  padding: 20px 30px;
  margin-bottom: 20px;
  .section-title {
    margin-bottom: 30px;
  }
  .border-top {
    padding-top: 30px;
    border-top: 1px solid #dcdfe6;
  }
}
</style>
