<template>
  <div class="container">
    <div class="box">
      <el-row :gutter="24">
        <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
          <el-form
            ref="form"
            :model="from"
            :inline="true"
            label-width="150px"
            :rules="rules"
          >
            <el-form-item label="实际报销人" prop="userName">
              <el-input v-model="from.userName" disabled></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="userPhone">
              <el-input v-model="from.userPhone" disabled></el-input>
            </el-form-item>
            <el-form-item label="项目名称" prop="projectId">
              <el-select v-model="from.projectId" placeholder="请选择">
                <el-option
                  v-for="item in projectList"
                  :key="item.projectId"
                  :label="item.projectName"
                  :value="item.projectId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="摘要" prop="summary">
              <el-input v-model="from.summary"></el-input>
            </el-form-item>

            <el-form-item
              label="报销总金额-大写(元)"
              prop="applyTotalAmountLarge"
            >
              <el-input
                v-model="from.applyTotalAmountLarge"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item
              label="报销总金额-小写(元)"
              prop="applyTotalAmountSmall"
            >
              <el-input
                v-model="from.applyTotalAmountSmall"
                @change="convertCurrency(from.applyTotalAmountSmall)"
              ></el-input>
            </el-form-item>
            <el-form-item prop="invoiceIdList" label="发票号码">
              <el-select
                v-model="from.invoiceIdList"
                multiple
                required
                filterable
                default-first-option
                placeholder="请选择发票号码"
                @change="getmoney()"
              >
                <el-option
                  v-for="item in getinvoivelist"
                  :key="item.invoiceId"
                  :label="item.number"
                  :value="item.invoiceId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-input v-model="from.paymentMethod"></el-input>
            </el-form-item>
            <br />
            <el-form-item>
              <el-button
                type="success"
                icon="el-icon-upload2"
                @click="updateForm()"
                >修改</el-button
              >
              <el-button
                type="info"
                icon="el-icon-refresh-left"
                @click="resetForm()"
                >重置信息</el-button
              >
              <el-button @click="back()">返回</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- 报销项 -->
        <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
          <div>
            <el-form
              :model="from"
              :inline="true"
              ref="details"
              label-width="150px"
            >
              <el-row
                v-for="(item, index) in from.reimbursementDetailsList"
                :key="index"
              >
                <el-col>
                  <el-form-item
                    :label="item.name"
                    :prop="'reimbursementDetailsList.' + index + '.money'"
                    :rules="{
                      validator: moneyrow,
                      trigger: 'blur',
                      required: true,
                    }"
                  >
                    <el-input v-model="item.money"
                      ><i
                        slot="suffix"
                        style="font-style: normal; margin-right: 10px"
                        >元</i
                      ></el-input
                    >
                  </el-form-item>
                  <el-form-item label="备注">
                    <el-input v-model="item.remarks"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { selectById } from "@/api/company";
import {
  selectById as reimbursementSelectById,
  update,
} from "@/api/reimbursement";
import { money } from "@/utils/myValidate";
import { selectAll as projectSelectAll, selectAllById } from "@/api/project";
import { selectByReimbursementId } from "@/api/reimbursementDetails";
import {
  selectAllBystatus,
} from "@/api/project";
export default {
  data() {
    return {
      reimbursementItemData: {
        list: [],
      },
      reimbursementItemList: [],
      company: {},
      timeNow: null,
      projectList: [],
      typeList: [],
      from: {
        userName: null, //申报人
        userPhone: null, //联系电话
        userId: null, //申报人Id
        summary: null, //摘要
        enclosureNumber: 0, //附件数量
        fillingTime: null, //填报日期
        applyTotalAmountLarge: null, //申请报销总金额（大写）
        applyTotalAmountSmall: null, //申请报销总金额（小写）
        paymentMethod: null, //支付方式
        reimbursementState: 0, //状态
        projectId: null, //项目id
        typeId: null, //报销类别id
        invoiceId: null,
        money: "", //备注
        fromList: [], //发票号码
        invoiceIdList: [], //发票号码
        reimbursementDetailsList: [], //报销项
      },
      //发票编号数组
      getinvoivelist: [],
      invoiceQurey: {
        companyId: null,
        reimbursementId: null,
      },
      rules: {
        typeId: [
          { required: true, message: "请选择报销类别", trigger: "change" },
        ],
        projectId: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        applyTotalAmountLarge: [
          {
            required: true,
            message: "请输入申请报销总金额（大写）",
            trigger: "blur",
          },
        ],
        applyTotalAmountSmall: [
          { validator: money, trigger: "blur", required: true },
        ],
        invoiceIdList:[
          {required: true, message: "请选择发票号码", trigger: "change" }
        ]
      },
      getlist:[],
    };
  },
  created() {
    //v-model 绑定的数据this.from.userId
    //this.$store.getters.info.userId 拿来query传过来的参数
    this.from.userId = this.$store.getters.info.userId;
    this.from.userName = this.$store.getters.info.userName;
    this.from.userPhone = this.$store.getters.info.userPhone;
    this.from.money = this.$store.getters.info.money;
    this.from.fromList = this.$store.getters.info.fromList;
    this.getFrom();
    this.getReimbursement();
    this.getProject();
    this.Selectinsertlsit();
    
  },
  computed: {
    reimbursementId() {
      return this.$route.query.id;
    },
  },
  methods: {
    //
    //获取报销类型显示(相当于详情)
    getReimbursement() {
      selectByReimbursementId({
        reimbursementId: this.$route.query.reimbursementId,
      })
        .then((res) => {
          if (res.success) {
            this.from.reimbursementDetailsList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("获取报销项失败");
        });
    },
    //获取报销信息
    getFrom() {
      //接收query传给我们的值
      (this.from.reimbursementId = this.$route.query.reimbursementId),
        (this.from.projectId = this.$route.query.projectId),
        (this.from.typeId = this.$route.query.typeId),
        (this.from.applyTotalAmountLarge =
          this.$route.query.applyTotalAmountLarge),
        (this.from.applyTotalAmountSmall =
          this.$route.query.applyTotalAmountSmall),
        (this.from.summary = this.$route.query.summary),
        (this.from.paymentMethod = this.$route.query.paymentMethod);
         this.getReimbursement();
    },
    //获取个人的项目
    getProject() {
      projectSelectAll({ userId: this.from.userId })
        .then((res) => {
          if (res.success) {
            this.projectList = res.data;
          } else {
            this.$message.error(res.msg);
            if (res.code == 4) {
              //执行退出功能
              this.$store.dispatch("user/logout");
              this.$router.push(`/login?redirect=${this.$route.fullPath}`);
            }
          }
        })
        .catch((error) => {
          this.$message.error("获取个人项目失败，无法申请报销");
        });
    },
    //获取公司名称
    getCompany() {
      selectById({ companyId: this.$store.getters.companyId })
        .then((res) => {
          if (res.status == "success") {
            this.company = res.data;
          } else {
            this.$message.error(res.data);
            if (res.code == 4) {
              //执行退出功能
              this.$store.dispatch("user/logout");
              this.$router.push(`/login?redirect=${this.$route.fullPath}`);
            }
          }
        })
        .catch((error) => {
          this.$message.error("获取公司名称失败");
        });
    },
    //获取发票金额
    getmoney() {
      this.from.applyTotalAmountSmall = 0;
      this.from.invoiceIdList.forEach((id)=>{
        this.getinvoivelist.forEach((e) => {
          if (e.invoiceId == id) {
            this.from.applyTotalAmountSmall += e.mone;
          }
        });
      })
      if (this.from.invoiceIdList.length == 0) {
        this.from.applyTotalAmountLarge = null;
      }
      this.convertCurrency(this.from.applyTotalAmountSmall);
    },
    //修改
    updateForm() {
      //金额的校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          //第一次校验左边
          this.$refs.details.validate((valid2) => {
            if (valid2) {
              let sumMoney = 0;
              this.from.reimbursementDetailsList.forEach((m) => {
                sumMoney += Number(m.money);
              });
              if (sumMoney != this.from.applyTotalAmountSmall) {
                this.$message.error("报销项总金额要等于报销总金额");
                return;
              }
              update(this.from)
                .then((res) => {
                  if (res.success) {
                    this.$message.success("修改成功，等待审批");
                    this.back();
                  } else {
                    this.$message.error(res.msg);
                  }
                })
                .catch((error) => {
                  this.$message.error("申请失败");
                });
            } else {
              this.$message.error("金额错误");
            }
          });
        }
      });
    },
    //获取现在时间
    time(data) {
      let date = new Date(data);
      var Y = date.getFullYear();
      var M =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var m =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      this.timeNow = Y + "年" + M + "月" + D + "日";
    },
    //返回
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({ path: "/reimbursementList" });
    },
    //重置信息
    resetForm() {
      this.getFrom();
      this.from.invoiceIdList=this.getlist;
    },
    //查询未报销的发票编号
    Selectinsertlsit() {
      let param = {
        companyId: this.$store.getters.companyId,
        status: 0,
        type: 2,
        userId: this.$store.getters.info.userId,
      };
      let list = [];
      selectAllBystatus(param)
        .then((res) => {
          if (res.success) {
            this.getinvoivelist = res.data;
            this.getinvoive({
              companyId: this.$store.getters.companyId,
              reimbursementId: this.from.reimbursementId,
            });
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch((error) => {
          this.$message.error("获取发票编号失败");
          this.back();
        });
    },
    //获取已报销的发票
    getinvoive(data) {
      selectAllById(data).then((res) => {
        if (res.success) {
          res.data.forEach((e) => {
            this.getinvoivelist.push(e)
            this.getlist.push(e.invoiceId)
            this.from.invoiceIdList.push(e.invoiceId);
          });
        }
      });
    },
    //定义金额校验
    moneyrow(rule, value, callback) {
      let RegExp =
        /(^([-]?)[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^([-]?)(0){1}$)|(^([-]?)[0-9]\.[0-9]([0-9])?$)/;
      // /^(([1-9][0-9]{0,14})|([0]{1})|(([0]\\.\\d{1,2}|[1-9][0-9]{0,14}\\.\\d{1,2})))$/;
      if (RegExp.test(value)) {
        callback();
      } else {
        callback(new Error("金额格式错误"));
      }
    },
    //金额转大小写
    convertCurrency(money) {
      //汉字的数字
      var cnNums = new Array(
        "零",
        "壹",
        "贰",
        "叁",
        "肆",
        "伍",
        "陆",
        "柒",
        "捌",
        "玖"
      );
      //基本单位
      var cnIntRadice = new Array("", "拾", "佰", "仟");
      //对应整数部分扩展单位
      var cnIntUnits = new Array("", "万", "亿", "兆");
      //对应小数部分单位
      var cnDecUnits = new Array("角", "分", "毫", "厘");
      //整数金额时后面跟的字符
      var cnInteger = "整";
      //整型完以后的单位
      var cnIntLast = "元";
      //最大处理的数字
      var maxNum = 999999999999999.9999;
      //金额整数部分
      var integerNum;
      //金额小数部分
      var decimalNum;
      //输出的中文金额字符串
      var chineseStr = "";
      //分离金额后用的数组，预定义
      var parts;
      if (money == "") {
        return "";
      }
      money = parseFloat(money);
      if (money >= maxNum) {
        //超出最大处理数字
        return "";
      }
      if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
      }
      //转换为字符串
      money = money.toString();
      if (money.indexOf(".") == -1) {
        integerNum = money;
        decimalNum = "";
      } else {
        parts = money.split(".");
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
      }
      //获取整型部分转换
      if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
          var n = integerNum.substr(i, 1);
          var p = IntLen - i - 1;
          var q = p / 4;
          var m = p % 4;
          if (n == "0") {
            zeroCount++;
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0];
            }
            //归零
            zeroCount = 0;
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m == 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        chineseStr += cnIntLast;
      }
      //小数部分
      if (decimalNum != "") {
        var decLen = decimalNum.length;
        for (var i = 0; i < decLen; i++) {
          var n = decimalNum.substr(i, 1);
          if (n != "0") {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (chineseStr == "") {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (decimalNum == "") {
        chineseStr += cnInteger;
      }
      this.from.applyTotalAmountLarge = chineseStr;
    },
  },
};
</script>
<style scoped>
.container {
  padding: 20px;
}
.clearfloat:after {
  /*伪元素是行内元素 正常浏览器清除浮动方法*/
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.no-border {
  border: none;
}
.show-border {
  border: 1px solid black;
}
.table {
  margin-bottom: 20px;
}
.table td {
  height: 33px;
  padding: 4px;
}
.table_title {
  font-size: 22px;
  font-weight: 900;
  margin-bottom: 10px;
}
.table-header {
  text-align: left;
}
.table-header > th {
  height: 50px;
  padding: 10px;
}
.herder-title {
  width: 100%;
}
.herder-title .title {
  float: left;
  text-align: left;
}
.sign {
  width: 100%;
  margin-bottom: 15px;
  padding-left: 10px;
}
.sign > div {
  width: 33%;
  float: left;
  font-size: 14px;
  font-weight: 900;
}
.data {
  width: 38%;
  float: right;
  font-size: 14px;
  font-weight: 900;
}
.items {
  text-align: center;
}

.td-input {
  display: inline-block;
  width: 100%;
  height: 100%;
  outline: none;
  border: none;
}
.input {
  outline: none;
  border: none;
}

.box {
  width: 100%;
  float: left;
  margin: 60px 0px;
  padding: 20px 10px;
  border-radius: 30px;
}
</style>