<template>
  <div class="container">
    <!-- 左边 -->
    <div class="box">
      <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="fromList">
          <el-select
            v-model="from.fromList"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择"
          >
            <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="summary">
          <el-input v-model="from.summary"></el-input>
        </el-form-item>
        <el-form-item label="报销总金额-大写(元)">
          <el-input v-model="from.applyTotalAmountLarge" disabled></el-input>
        </el-form-item>
        <el-form-item
          label="报销总金额-小写(元)"
          prop="applyTotalAmountSmall"
          :rules="{ validator: moneyrow, trigger: 'blur', required: true }"
        >
          <el-input
            v-model="from.applyTotalAmountSmall"
            @change="convertCurrency(from.applyTotalAmountSmall)"
          ></el-input>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-input v-model="from.paymentMethod"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="from.remarks"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="附件描述">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="from.enclosureDescribe"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload
            class="upload-demo"
            drag
            ref="enclosureUpload"
            :action="action1"
            :auto-upload="false"
            :data="enclosurelist"
            multiple
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <br />
        <el-form-item>
          <el-button
            type="success"
            icon="el-icon-upload2"
            @click="submitForm()"
            :disabled="subbut"
            >提交</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>
    </div>
    <!-- 右边 -->
    <div>
      <div class="spend" v-show="!subbut">
        <el-form
          :model="reimbursementItemData"
          :inline="true"
          label-width="150px"
          ref="details"
        >
          <el-row
            v-for="(item, index) in reimbursementItemData.list"
            :key="index"
          >
            <el-col>
              <el-form-item
                :label="item.itemNamwe"
                :prop="'list.' + 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>
      <div v-show="subbut">
        <el-empty description="暂无报销项，因此无法报销"></el-empty>
      </div>
    </div>
  </div>
</template>
<script>
import { selectAllCompanyId } from "@/api/reimbursementItem";
import { selectAll as projectSelectAll } from "@/api/project";
import { insert } from "@/api/reimbursement";
import { Details } from "@/api/reimbursement";
import { queryBypageIncomeAdd, selectAllBystatus } from "@/api/project";
import { updatesubmit } from "@/api/project";
export default {
  data() {
    return {
      //提交信息
      from: {
        // list1:[],
        companyId: null, //公司id
        userName: null, //申报人
        userPhone: null, //联系电话
        userId: null, //申报人Id
        summary: null, //摘要
        enclosureNumber: 0, //附件数量
        fillingTime: null, //填报日期
        applyTotalAmountLarge: null, //申请报销总金额（大写）
        applyTotalAmountSmall: null, //申请报销总金额（小写）
        paymentMethod: null, //支付方式
        reimbursementState: 0, //状态
        projectId: null, //项目id
        fromList: [], //发票号码
        remarks: "", //备注
        enclosureDescribe: "", //附件描述
      },
      projectList: [], //项目列表
      getinvoivelist: [], //可以选择的发票号
      subbut: false, //是否有报销项
      //右边表单数据
      reimbursementItemData: {
        list: [],
      },
      reimbursementItemList: [],

      //表单验证内容
      rules: {
        typeId: [
          { required: true, message: "请选择报销类别", trigger: "change" },
        ],
        fromList: [
          { required: true, message: "请选择发票号码", trigger: "change" },
        ],
        projectId: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        number: [
          { required: true, message: "请输入发票号码", trigger: "change" },
        ],
        code: [
          { required: true, message: "请输入发票代码", trigger: "change" },
        ],
        category: [
          {
            required: true,
            message: "请至少选择一个发票类型",
            trigger: "change",
          },
        ],
        type: [
          {
            required: true,
            message: "请至少选择一个发票类别",
            trigger: "change",
          },
        ],
        mone: [
          { required: true, message: "请输入发票金额", trigger: "change" },
        ],
      },
      isgetid: 0,
      //查询发票参数
      invoicegetQurey: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
      },
      action1: null, //附件图片提交地址
      fileTypeJpg: false, //判断是否有发票文件且格式正确
      Uploadstatus: false, //判断文件上传的状态
      //附件提交附带参数  那个data本来就没有参数
      enclosurelist: {
        Id: null,
        companyId: 0,
        enclosureDescribe: "",
        status: 2,
        userId: 0,
      },
    };
  },
  created() {
    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.companyId = this.$store.getters.companyId;
    this.invoicegetQurey.companyId = this.$store.getters.companyId;
    this.action1 = process.env.VUE_APP_BASE_API + "/file/updataEnclosures";
    this.time();
    this.getProject();
    this.getReimbursement();
    this.Selectinsertlsit();
  },
  methods: {
    //上传附件
    enclosure() {
      this.drawer1 = true;
    },
    //提交
    submitForm() {
      this.$refs.form.validate((valid1) => {
        if (valid1) {
          this.$refs.details.validate((valid) => {
            if (valid) {
              insert(this.from)
                .then((res) => {
                  if (res.success) {
                    //上传发票号
                    let list = [];
                    this.from.fromList.forEach((item) => {
                      list.push({
                        invoiceId: item,
                        reimbursementId: res.data,
                        status: 1,
                      });
                    });
                    updatesubmit(list).then((res) => {
                      if (res.success) {
                        this.$message.success(res.msg);
                      } else {
                        this.$message.error("发票绑定失败");
                      }
                    });
                    console.log(res);
                    // 上传附件
                    this.enclosurelist.Id = res.data;
                    this.enclosurelist.companyId = this.from.companyId;
                    this.enclosurelist.enclosureDescribe =
                    this.from.enclosureDescribe;
                    this.enclosurelist.userId = this.from.userId;
                    this.$refs.enclosureUpload.submit();
                    // this.$message.success("上传附件成功");
                    //上传右边的报销项了 ，上传报销项之前，需要处理数据reimbursementId代表着本次提交报销表的id
                    this.reimbursementItemData.list.forEach((item) => {
                      item.reimbursementId = res.data; //reimbursementId 放到原本data里面
                    });
                    Details(this.reimbursementItemData.list).then((res) => {
                      if (res.success) {
                        // this.$message.success(res.msg);
                        this.back();
                      } else {
                        this.$message.error(res.msg);
                      }
                    });
                  } else {
                    this.$message.error(res.msg);
                  }
                })
                .catch((error) => {
                  console.log(error);
                  this.$message.error("提交失败");
                });
            }
          });
        }
      });
    },
    //重置信息
    resetForm() {
      this.$refs.form.resetFields(); //resetFields重置表单
      this.time();
      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.companyId = this.$store.getters.companyId;
    },
    //返回
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({ path: "/reimbursementList" });
    },
    //获取现在时间
    time() {
      let date = new Date();
      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.from.fillingTime =
        Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s;
    },
    //获取个人的项目
    getProject() {
      projectSelectAll({ userId: this.from.userId })
        .then((res) => {
          if (res.success) {
            this.projectList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("获取个人项目失败，无法申请报销");
        });
    },
    //获取报销项
    getReimbursement() {
      let param = {
        companyId: this.$store.getters.companyId,
      };
      selectAllCompanyId(param)
        .then((res) => {
          if (res.success) {
            //获取数据
            let reimbursementItemList = res.data;
            if (reimbursementItemList.length == 0) {
              this.subbut = true;
            } else {
              this.subbut = false;
              //处理数据
              reimbursementItemList.forEach((e) => {
                //设置参数
                let pram = {
                  itemNamwe: e.name,
                  itemId: e.id,
                  money: 0,
                  reimbursementId: null,
                  remarks: null,
                };
                this.reimbursementItemData.list.push(pram);
              });
            }
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("获取报销项失败");
        });
    },
    //定义金额校验
    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("金额格式错误"));
      }
    },
    //查询发票
    getincomeSelectlist(pager = 1) {
      this.invoicegetQurey.pageNum = pager;
      queryBypageIncomeAdd(this.invoicegetQurey)
        .then((res) => {
          if (res.success) {
            this.invoicegetList = res.data.list;
            this.total = res.data.total;
          } else {
            this.$message.errror(res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("查询发票数据失败");
        });
    },

    //取消
    cancel() {
      this.isgetid = 0;
      this.getincomeSelectlist();
    },
    //清除图片片文件
    delfile2(file, fileList) {
      this.fileTypeJpg = false;
    },
    //查询发票编号
    Selectinsertlsit() {
      let param = {
        companyId: this.$store.getters.companyId,
        status: 0,
        type: 2,
        userId: this.$store.getters.info.userId,
      };
      // console.log(this.getinvoivelist)
      selectAllBystatus(param)
        .then((res) => {
          if (res.success) {
            this.getinvoivelist = res.data;
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch((error) => {
          this.$message.error("获取发票编号失败");
          this.back();
        });
    },
    //金额小写转大写
    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;
  /* min-width : 0 */
}
</style>

<style scoped>
.box {
  width: 800px;
  float: left;
  margin: 60px 0px;
  padding: 20px 10px;
  border-radius: 30px;
  /* white-space: nowrap; */
}
.spend {
  width: 800px;
  float: left;
  margin: 60px 0px;
  padding: 20px 10px;
  /* white-space: nowrap; */
}
</style>