<template>
  <div class="h100 font14">
    <van-popup
      id="creditPopup"
      v-model="show"
      closeable
      position="bottom"
      :style="{ height: '100%' }"
      @close="popupClose"
    >
      <van-nav-bar title="资信额度申请"/>

      <form>
        <div class="item">
          <div class="left normal-normal-font">客户信息</div>
          <div
            class="right"
          >{{moreSearchInfo.post.comPartyId}}/({{clientInfo.partyOpcode}}){{clientInfo.clientName}}</div>
        </div>
        <div class="item">
          <div class="left normal-normal-font">
            申请额度
            <b>*</b>
          </div>
          <div class="right">
            <van-field v-model="applyLimit" type="number" placeholder="请输入申请额度"/>
          </div>
        </div>
        <div class="item">
          <div class="left normal-normal-font">
            申请天数
            <b>*</b>
          </div>
          <div class="right">
            <van-field v-model="applyDate" type="digit" placeholder="请输入申请天数"/>
          </div>
        </div>
        <div class="item" :style="{paddingBottom:'14px'}">
          <div class="left normal-normal-font">
            本月承诺回笼金额
            <b>*</b>
          </div>
          <div class="right">
            <van-field v-model="thisMon" type="number" placeholder="请输入回笼金额"/>
          </div>
        </div>

        <div class="item" id="bmp-user" @click="bmpShowChange(true)">
          <van-cell :value="bmpUser.CNNAME ? bmpUser.CNNAME : bmpUser.cnname" is-link>
            <template #title>
              <span class="normal-normal-font">指定审批人</span>
              <b v-if="bmpIs">*</b>
            </template>
          </van-cell>
        </div>
        <div v-if="!bmpIs">
          <div class="item">
            <div class="left normal-normal-font">附件上传</div>
            <div class="right">
              <van-uploader :after-read="onRead" :max-size="2 * 1024 * 1024" @oversize="onOversize">
                <van-button type="primary" size="small">选择附件</van-button>
              </van-uploader>
            </div>
          </div>
          <div class="item taps">
            <div>最多上传10个，每个文件不得超过2M</div>
          </div>
          <div class="item" v-for="( item,index ) in fileList" :key="index">
            <div class="left normal-normal-font van-ellipsis">{{item.attachmentName}}</div>
            <div class="right">
              <van-icon name="close" @click="delImg(index)"/>
            </div>
          </div>
        </div>
        <div class="item files-top">
          <div class="left normal-normal-font">
            申请理由
            <b>*</b>
          </div>
        </div>
        <div class="reason">
          <div class="item">
            <van-checkbox class="normal-normal-font" v-model="checked1">跳票</van-checkbox>
            <div class="light-normal-font" @click="chooseDate('tpDate')">{{tpDate}}</div>
            <div class="normal-normal-font">解决</div>
          </div>
          <div class="item">
            <van-checkbox class="normal-normal-font" v-model="checked2">贷款回笼</van-checkbox>
            <div class="light-normal-font" @click="chooseDate('hlDate')">{{hlDate}}</div>
            <div class="normal-normal-font">核销</div>
          </div>
          <div class="item" @click="checked3 = !checked3">
            <van-checkbox class="normal-normal-font" v-model="checked3">超期</van-checkbox>
          </div>
          <div class="item" v-show="checked3">
            <van-field
              v-model="chaoqiTxt"
              rows="3"
              autosize
              type="textarea"
              maxlength="50"
              show-word-limit
            />
          </div>
          <div class="item" @click="checked4 = !checked4">
            <van-checkbox class="normal-normal-font" v-model="checked4">超额</van-checkbox>
          </div>
          <div class="item" v-show="checked4">
            <!-- <input type="text" v-model="chaoeTxt"> -->
            <van-field
              v-model="chaoeTxt"
              rows="3"
              autosize
              type="textarea"
              maxlength="50"
              show-word-limit
            />
          </div>
        </div>
        <div class="botton-btn" id="submitBtn">
          <div class="left" @click="consoleApped">取消</div>
          <div class="right" @click="appedCredit">提交</div>
        </div>
      </form>
    </van-popup>
    <bmp-user v-model="bmpShow" @getBmpUser="getBmpUser" @bmpUserClose="bmpShowChange"></bmp-user>
    <van-popup v-model="showTimeDialog" get-container="body" close-icon="close" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        v-if="showTimeDialog"
        @confirm="confirm"
        @cancel="cancel"
        :formatter="formatter"
      />
    </van-popup>
  </div>
</template>

<script>
import BmpUser from "./BmpUser";
import { getFormateDate } from "@/utils/common";
import {
  uploadImg,
  appedCreditHttp,
  checkCompanyNum
} from "@/api/clientprofile";
import { Dialog } from "vant";
export default {
  name: "AppedCredit",
  components: { BmpUser },
  data() {
    return {
      show: false,
      order: {},
      applyLimit: "", //申请额度
      applyDate: "", //申请天数
      thisMon: "", //月回收金额
      bmpUser: { CNNAME: "请选择" },
      checked1: false,
      checked2: false,
      checked3: false,
      checked4: false,
      chaoqiTxt: "",
      chaoeTxt: "",
      bmpShow: false,
      showTimeDialog: false, //日期选择弹窗
      currentDate: new Date(), //当前日期
      tpDate: getFormateDate(new Date(), "yyyy-MM-dd"), //跳票日期
      hlDate: getFormateDate(new Date(), "yyyy-MM-dd"), //跳票日期
      selector: "",
      bpmTestDb: "", //新老接口数据源
      bmpIs: true, //bmp是否必选
      fileList: [],
      file: "",
      applyreason: "" //提交原因
    };
  },
  computed: {
    linkInfo() {
      return this.$store.state.linkInfo;
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    bmpShowg: {
      type: Boolean,
      default: false
    },
    moreSearchInfo: {
      type: Object,
      default: { post: { comPartyId: "" } }
    },
    clientInfo: {
      type: Object,
      default: {
        partyOpcode: "",
        clientName: ""
      }
    }
  },
  watch: {
    value(val) {
      this.show = val;
    },
    bmpShowg(val) {
      this.bmpShow = val;
    },
    bmpShow(val) {
      this.$emit("onBmpCloseg", val);
    }
  },
  methods: {
    // 文件超过2m
    onOversize(file) {
      console.log(file);
      this.$toast("此文件大小超过2m，上传失败");
    },
    // 文件上传
    onRead(file) {
      if (
        ![
          "gif",
          "jpg",
          "jpeg",
          "bmp",
          "png",
          "doc",
          "docx",
          "xls",
          "xlsx",
          "pdf",
          "ppt",
          "pptx",
          "txt"
        ].includes(file.file.name.split(".").pop())
      ) {
        this.$toast(
          "只能上传gif、jpg、jpeg、bmp、png、doc、docx、xls、xlsx、pdf、ppt、pptx、txt格式的文件"
        );
        return;
      }
      if (this.fileList.length >= 10) {
        this.$toast("文件数量超过10个，上传失败");
      } else {
        this.file = file;
        let fd = new FormData();
        fd.append("file", file.file);
        fd.append("username", this.linkInfo.userId);
        uploadImg(fd).then(rt => {
          if (rt.code == 200) {
            this.fileList.push({
              attachmentDownloadUrl:
                process.env.HOST_URL +
                process.env.PORT +
                process.env.BASE_URL +
                rt.data.localdownloadurl,
              attachmentName: this.file.file.name,
              attachmentSize: this.file.file.size,
              attachmentType: this.file.file.type
            });
          } else {
            this.$toast("上传失败");
          }
        });
      }
    },
    // 文件删除
    delImg(index) {
      Dialog.alert({
        message: "确定要删除附件吗？"
      }).then(() => {
        this.fileList.splice(index, 1);
      });
    },
    // 提交申请
    appedCredit() {
      let applyreason = ["", "", "", ""];
      if (this.checked1) {
        applyreason[0] = "跳票:" + this.tpDate + " 解决";
      } else {
        applyreason[0] = "";
      }
      if (this.checked2) {
        applyreason[1] = "贷款回笼:" + this.tpDate + " 解决";
      } else {
        applyreason[1] = "";
      }
      if (this.checked3) {
        applyreason[2] = "超期:" + this.chaoqiTxt;
      } else {
        applyreason[2] = "";
      }
      if (this.checked4) {
        applyreason[3] = "超额:" + this.chaoeTxt;
      } else {
        applyreason[3] = "";
      }
      this.applyreason = applyreason.filter(value => value != "").join(";");

      Dialog.confirm({
        message: "确认提交申请吗？"
      })
        .then(() => {
          let param = {
            attr: {
              BIZTRANSACTIONID: "11",
              accorgid: "",
              affirmamount: "",
              id: "0",
              instid: "0",
              affirmday: "",
              applierid: this.linkInfo.sysUserId,
              appliername: this.linkInfo.userName,
              applylimits: this.applyLimit, //申请额度
              applyno: "",
              applyreason: this.applyreason, //申请理由
              applyturndays: this.applyDate, //申请天数
              arbalance: "",
              attr1: "",
              attr10: "",
              attr12: "",
              attr2: "",
              attr3: "",
              attr4: "",
              attr5: "",
              attr6: "",
              attr7: "",
              attr8: "",
              attr9: "",
              bpmcreatedept: "",
              bpmcreateuser: "",
              cewcq: "",
              cewcqreason1: "",
              cewcqreason2: "",
              checkedlimits: "",
              clientcode: this.moreSearchInfo.post.partyOpcode, //客户编码
              clientname: this.moreSearchInfo.post.partyName, //客户名称
              clientpartyid: this.moreSearchInfo.post.comPartyId, //客户ID
              clientstyle: "",
              comclientid: "",
              contacttel: "",
              cqhkwh: "",
              cqhkwhreason: "",
              cqhkwhresolve: "",
              creditlevel: "",
              creditover: "",
              curcycledays: "",
              cycledays: "",
              daybegindate: "",
              dayenddate: "",
              ddts: "",
              deptid: "",
              ds: "",
              invuser: this.linkInfo.sysOrgId,
              invusername: "",
              jydtts: "",
              kyje: "",
              limitdays: "",
              monthrtl: "",
              moveflag: "",
              promisereturn: this.thisMon, //本月承诺回笼金额
              salerid: "",
              salername: "",
              sdje: "",
              sjye: "",
              sscclientctlid: "",
              totalgathering: "",
              totalsales: "",
              tp: "",
              tpreason: "",
              tpresolve: "",
              ts: "",
              tsend: "",
              tswje: "",
              unbook: "",
              viewcreditid: "",
              ye: "",
              yearrtl: "",
              yfbalance: "",
              ytdsales: "",
              applydate: "",
              begindate: "",
              checkdate: "",
              enddate: "",
              overstartdate: "",
              overstopdate: "",
              promisedate: "",
              approvaluser: this.bmpUser.EMPUID
                ? this.bmpUser.EMPUID
                : this.bmpUser.empid, //指定审批人
              createuser: "",
              parm1: "",
              parm2: "",
              parm3: "",
              DataSource: this.bpmTestDb
            },
            attrList: this.fileList
          };
          appedCreditHttp(param).then(rt => {
            if (this.bmpIs) {
              console.log(rt);
              this.$toast(rt.Body.appliedResponse.return.message);
              if (rt.Body.appliedResponse.return.code == 1) {
                this.consoleApped();
              }
            } else {
              console.log(rt);
              this.$toast(rt.message);
              if (rt.code == 1) {
                this.consoleApped();
              }
            }
          });
        })
        .catch(() => {});
      // 校验
      let reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
      if (this.applyreason.length > 200) {
        Dialog.alert({
          message: "申请理由不能超过200字！"
        }).then(() => {
          return;
        });
      }
      if (this.applyreason.length == "") {
        Dialog.alert({
          message: "申请理由不能为空！"
        }).then(() => {
          return;
        });
      }
      if (this.bmpIs) {
        if (this.bmpUser.CNNAME == "") {
          Dialog.alert({
            message: "指定审批人必须选择"
          }).then(() => {
            return;
          });
        }
      } else {
        if (!this.bpmTestDb) {
          Dialog.alert({
            message: "未设置BPM账号,无法发起申请,请联系管理员"
          }).then(() => {
            return;
          });
        }
      }
      if (!reg.test(this.thisMon)) {
        Dialog.alert({
          message: "本月承诺回笼金额：请输入大于0的整数或保留两位小数"
        }).then(() => {
          this.thisMon = "";
        });
      }
      if (!/^\d+$/.test(this.applyDate)) {
        Dialog.alert({
          message: "申请天数：请输入大于0的整数"
        }).then(() => {
          this.applyDate = "";
        });
      }
      if (!reg.test(this.applyLimit)) {
        Dialog.alert({
          message: "申请额度：请输入大于0的整数或保留两位小数"
        }).then(() => {
          this.applyLimit = "";
        });
      }
    },
    // 关闭
    consoleApped() {
      this.applyLimit = "";
      this.applyreason = "";
      this.applyDate = "";
      this.thisMon = "";
      this.bmpUser = { CNNAME: "请选择" };
      this.checked1 = false;
      this.checked2 = false;
      this.checked3 = false;
      this.checked4 = false;
      this.chaoqiTxt = "";
      this.chaoeTxt = "";
      this.tpDate = getFormateDate(new Date(), "yyyy-MM-dd");
      this.hlDate = getFormateDate(new Date(), "yyyy-MM-dd");
      this.fileList = [];
      this.file = "";
      this.show = false;
    },
    // 关闭
    popupClose() {
      this.consoleApped();
      this.$emit("onappedClose", false);
    },
    // bmp选择
    bmpShowChange(data) {
      this.bmpShow = data;
      if (this.bmpShow) {
        window.history.pushState(null, null, document.URL);
      }
    },
    // 获取bmpUser
    getBmpUser(data) {
      if (data) {
        this.bmpUser = data;
      }
    },
    // 日期选择器相关
    formatter(type, val) {
      if (type === "year") {
        return `${val}年`;
      } else if (type === "month") {
        return `${val}月`;
      } else if (type === "day") {
        return `${val}日`;
      }
      return val;
    },
    confirm(data) {
      if (this.selector == "tpDate") {
        this.tpDate = getFormateDate(this.currentDate, "yyyy-MM-dd");
      } else if (this.selector == "hlDate") {
        this.hlDate = getFormateDate(this.currentDate, "yyyy-MM-dd");
      }
      this.showTimeDialog = false;
    },
    cancel() {
      this.showTimeDialog = false;
    },
    chooseDate(type) {
      this.selector = type;
      // this.currentDate = new Date(this[type])
      this.showTimeDialog = true;
    },
    getDataSource() {}
  },
  // 判断公司相应的逻辑
  created() {
    // 有4家公司审批人必选，使用老接口，无文件上传功能
    console.log(111);
    let params = {
      attr: {
        companyname: this.linkInfo.sysCompanyName,
        sysname: "BPM",
        empid: this.linkInfo.userId,
        userid: ""
      },
      dbName: "",
      length: "10",
      start: "1"
    };
    checkCompanyNum(params)
      .then(resp => {
        let companynames = resp.sysCompany;
        // if (
        //   resp.companyname == "上药控股有限公司" ||
        //   resp.companyname == "上药康德乐罗达（上海）医药有限公司" ||
        //   resp.companyname == "上药科泽（上海）医药有限公司" ||
        //   resp.companyname == "上药闵行（上海）医药有限公司(合并)"
        // ) {
        //   this.bpmTestDb = "";
        //   this.bmpIs = true;
        // } else {
          this.bmpIs = false;
          if (companynames.data) {
            for (var i = 0; i < companynames.data.length; i++) {
              if (
                companynames.data[i].companyname == this.linkInfo.sysCompanyName
              ) {
                this.bpmTestDb = companynames.data[i].db_source;
                break;
              }
            }
          } else {
            //todo
          }
        // }
      })
      .catch(error => {
        this.$toast("获取db_source失败，请联系管理员");
      });
  },
  mounted() {
    // 处理安卓虚拟键盘顶起提交按钮的问题
    let screenHeight = document.body.offsetHeight;
    // 为window绑定resize事件
    window.onresize = function() {
      let nowHeight = document.body.offsetHeight;
      if (nowHeight < screenHeight) {
        // 将底部弹起的按钮隐藏（可使用给按钮添加相应消失类）
        // this.$refs.submitBtn.style.position = 'static'
        if (document.getElementById("submitBtn")) {
          document.getElementById("submitBtn").style.position = "static";
        }
        // document.getElementById('creditPopup').scrollTop = document.body.scrollHeight
      } else {
        // 将按钮正常显示（可使用给按钮移除相应消失类）
        if (document.getElementById("submitBtn")) {
          document.getElementById("submitBtn").style.position = "fixed";
        }
      }
    };
  }
};
</script>

<style lang="scss" scoped>
/deep/ #creditPopup .item .right input {
  text-align: right;
}
/deep/ #creditPopup textarea {
  border: 1px solid #bcc1cc;
  border-radius: 5px;
}
/deep/ #creditPopup input {
  text-align: right !important;
  border: none !important;
}
#creditPopup {
  .van-cell {
    font-size: 14px;
  }
  background-color: $bc2;
  .botton-btn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 50px;
    .left,
    .right {
      float: left;
      width: 50%;
      line-height: 50px;
      font-size: 16px;
      text-align: center;
      background-color: #fff;
    }
    .right {
      color: white;
      background: linear-gradient(to right, #02baf4 0%, #5341e7 100%);
    }
  }
  .van-nav-bar__title {
    color: $txtBlack;
    font-weight: 600;
    font-size: 15px;
  }
  form {
    height: calc(100vh - 51px);
    overflow: scroll;
    #bmp-user {
      .van-cell--clickable {
        padding: 0;
      }
      margin: 7px 0;
      .right {
        b {
          color: #6c727d;
          vertical-align: text-top;
          font-weight: 700;
        }
      }
    }
    .taps {
      color: red;
    }
    .files {
      margin-bottom: 3px;
      .right {
        .van-icon-close {
          vertical-align: text-top;
          font-weight: 700;
          font-size: 18px;
        }
      }
    }
    .files-top {
      margin-top: 7px;
    }
    .item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0;
      padding: 7px 14px;
      b {
        color: #e96625;
        vertical-align: middle;
      }
      .left {
        flex-shrink: 0;
        width: 150px;
        .van-ellipsis {
          width: 80%;
        }
      }
      .right {
        flex-grow: 1;
        padding-left: 10px;
        text-align: right;
        .van-field {
          padding: 0;
        }
        .van-field {
          text-align: right;
          padding: 3px 14px 3px 0;
          border: 1px solid rgba(188, 193, 204, 1);
          border-radius: 2px;
        }
      }
      .van-checkbox {
        width: 33.333%;
        .van-checkbox__label {
          color: #677282;
          margin-left: 15px;
        }
      }
    }
    .reason {
      margin-bottom: 50px;
      .item {
        padding-bottom: 10px;
        input {
          width: 100%;
        }
      }
    }
  }
}
</style>
