<template>
  <div class="addcontractdc-container">
    <el-form ref="form" :model="formData" label-position="left" :rules="formRule" label-width="110px">
      <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"
                :city-source="city_sorce"  :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">{{ formData.OriginalPrice | digitUppercase }}</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="关键词搜索" :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">
                    <div slot="content">没有正式转试用记录的客户，在申请转正时提交的合同</div>
                    <i class="el-icon-info" style="font-size: 14px; margin-left: -20px"></i>
                  </el-tooltip>
                </div>
                <div style="margin-right: 10px">
                  <el-radio label="续约合同" disabled>续约合同</el-radio>
                  <el-tooltip effect="dark" style="cursor: pointer; width: 20px">
                    <div slot="content">
                      1、有正式转试用记录的客户，在申请转正时提交的合同<br />
                      2、所有客户在续约申请时提交的合同
                    </div>
                    <i class="el-icon-info" style="font-size: 14px; margin-left: -20px"></i>
                  </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">{{ relationContractData.timeRange | formateYear }}</span>
          </div>

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

          <div class="flex border-top">
            <el-form-item label="优惠后金额" style="width: 50%">
              <el-input disabled :value="relationContractData.Price|formatPrice" placeholder="请输入优惠后金额" style="width: 220px"></el-input>
            </el-form-item>
            <span style="line-height: 40px">{{ relationContractData.Price | digitUppercase }}</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 :value="relationContractData.Remark?'1':'2'" label="2" disabled>无</el-radio>
          <el-radio :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('预览')">预览</el-button>
          <el-button type="primary" @click="handleSubmit('存草稿')" style="width: 145px">存草稿</el-button>
          <el-button type="primary" @click="handleSubmit('提交')" style="width: 145px">提交</el-button>
        </div>
      </section>
    </el-form>

    <!-- 选择合同弹窗 -->
    <el-dialog v-dialogDrag :title="`搜索到${formData.trueUseName}下合同`" :append-to-body="true" :visible.sync="showContractList" width="50%" center>
      <el-table :data="contractList" border height="60vh">
        <el-table-column align="center" width="50">
          <template slot-scope="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 slot-scope="scope">{{ scope.row.StartDateStr | formatTime }}~{{ scope.row.EndDateStr | formatTime }}</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 slot-scope="scope">{{ scope.row.CheckBackFileTimeStr | formatTime }}</template>
        </el-table-column>
      </el-table>
      <div style="text-align: center; margin: 30px 0">
        <el-button type="primary" @click="handleRelation">确定关联</el-button>
        <el-button type="primary" plain @click="showContractList = false">取消</el-button>
      </div>
    </el-dialog>

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

<script>
import { contractInterface } from "@/api/api.js";
import{province_sorce,city_sorce} from '@/utils/distpicker';
import QyServiceTable from "./components/QyServiceTable"; //权益服务内容表格组件
import FiccServiceTable from "./components/FiccServiceTable"; //ficc服务内容表格组件
import { CalculationDate } from "@/utils/CalculationDate";
export default {
  name: "addConstractDC",
  components: {
    QyServiceTable,
    FiccServiceTable,
  },
  filters: {
    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
    },
    // 金额转中文大写
    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(/^整$/, "零元整")
      );
    },
    //计算多少年
    formateYear(e) {
      if (e[0]) {
        return `有效期为${CalculationDate(e[0], e[1])}`;
      } else {
        return "";
      }
    },
  },
  data() {
    this.province_sorce=province_sorce
    this.city_sorce=city_sorce
    return {
      RoleType: localStorage.getItem("Role") || "",
      formData: {
        CompanyName: "",
        CreditCode: "",
        Province: "",
        City: "",
        Address: "",
        Fax: "",
        Phone: "",
        Postcode: "",
        OriginalPrice: "",
        trueUseName: "",
        sellerRemark: "",
        PayRemark: "",
        RelationContractId: null,
      },
      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" }],
      },
      searchList: [],
      contractList: [],
      showContractList: false,
      relationContractData: null, //选择的关联合同数据
      ficcServiceData: null, //ficc 底部表格数据
      qyServiceData: null, //权益底部表格数据
      serviceShow: false, //是否显示查看报价单
      serviceCon: {}, //选择的服务项 查看报价单/选择品种
    };
  },
  methods: {
    // 搜索出客户
    async customeSearch(query) {
      if (!query) return;
      const res = await contractInterface.getBusinessContractCompanyNameList({ Keyword: query });
      if (res.Ret === 200) {
        this.searchList = res.Data;
      }
    },

    // 选择客户并搜索出其下已签回合同
    async handleSelectTrueUseName(e) {
      if (e||!this.formData.trueUseName) return;
      const res = await contractInterface.getBusinessContractList({ CompanyName: this.formData.trueUseName });
      if (res.Ret === 200) {
        this.showContractList = true;
        this.$nextTick(() => {
          this.contractList = res.Data.List;
        });
      }
    },

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

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

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

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

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

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

    // 金额输入框获取焦点
    handlePriceBoxFocus(key){
      let val=this.formData[key]
      val=val.replace(/,/g,'')
      this.formData[key]=val
    },
    // 金额输入框获失去焦点
    handlePriceBoxBlur(key){
      let str=this.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
      }
      this.formData[key]=num1.replace(/(?!^)(?=(\d{3})+$)/g, ',')+num2
    }
  },
};
</script>

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