<template>
  <el-form
    ref="ruleform"
    :model="spendreimbursementform"
    label-width="120px"
    :rules="rules"
  >
    <el-main>
      <el-row :gutter="20">
        <!-- 第一列表单 -->
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <!-- projectId -->
            <el-form-item label="报销项目" prop="projectId">
              <el-select
                placeholder="请选择"
                v-model="spendreimbursementform.projectId"
              >
                <el-option
                  :label="item.projectName"
                  v-for="item in collectProject"
                  :key="item.projectId"
                  :value="item.projectId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <!-- summary -->
            <el-form-item label="摘要" prop="summary">
              <el-input v-model="spendreimbursementform.summary"></el-input>
            </el-form-item>
            <!-- enclosureNumber -->
            <el-form-item label="附件数量" prop="enclosureNumber">
              <el-input
                v-model.number="spendreimbursementform.enclosureNumber"
              ></el-input>
            </el-form-item>
            <!-- tripReason -->
            <el-form-item label="出差缘由" prop="tripReason">
              <el-input v-model="spendreimbursementform.tripReason"></el-input>
            </el-form-item>
            <!-- fromPlace -->
            <el-form-item label="出发地点" prop="fromPlace">
              <el-input v-model="spendreimbursementform.fromPlace"></el-input>
            </el-form-item>
            <!-- purposePlace -->
            <el-form-item label="目的地点" prop="purposePlace">
              <el-input
                v-model="spendreimbursementform.purposePlace"
              ></el-input>
            </el-form-item>
            <!-- transitPlace -->
            <el-form-item label="经过地点" prop="transitPlace">
              <el-input
                v-model="spendreimbursementform.transitPlace"
              ></el-input>
            </el-form-item>
            <!-- vehicle -->
            <el-form-item label="交通工具" prop="vehicle">
              <el-input v-model="spendreimbursementform.vehicle"></el-input>
            </el-form-item>
            <!-- applyTime -->
            <el-form-item label="申请时间" prop="applyTime" required>
              <el-date-picker
                v-model="spendreimbursementform.applyTime"
                type="date"
                style="width: 90%"
                @change="formtime3"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </div>
        </el-col>
        <!-- 第二列表单 -->
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <!-- receiveSubsidy -->
            <el-form-item label="是否领取补贴">
              <el-switch
                v-model="values"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeswitch(values)"
              >
              </el-switch>
            </el-form-item>

            <!-- foodAllowance -->
            <el-form-item label="伙食补贴" prop="foodAllowance">
              <el-input
                v-model="spendreimbursementform.foodAllowance"
                :disabled="
                  spendreimbursementform.receiveSubsidy == 1 ? false : true
                "
              ></el-input>
            </el-form-item>
            <!-- publicMiscellaneousSubsidy -->
            <el-form-item label="公杂补贴" prop="publicMiscellaneousSubsidy">
              <el-input
                v-model="spendreimbursementform.publicMiscellaneousSubsidy"
                :disabled="
                  spendreimbursementform.receiveSubsidy == 1 ? false : true
                "
              ></el-input>
            </el-form-item>
            <!-- tripCost -->
            <el-form-item label="火车/汽车/轮船费" prop="tripCost">
              <el-input v-model="spendreimbursementform.tripCost"></el-input>
            </el-form-item>
            <!-- planeTicket -->
            <el-form-item label="飞机票" prop="planeTicket">
              <el-input v-model="spendreimbursementform.planeTicket"></el-input>
            </el-form-item>
            <!-- trafficCost -->
            <el-form-item label="过路过桥汽油费" prop="trafficCost">
              <el-input v-model="spendreimbursementform.trafficCost"></el-input>
            </el-form-item>
            <!-- lodgingCost -->
            <el-form-item label="住宿费" prop="lodgingCost">
              <el-input v-model="spendreimbursementform.lodgingCost"></el-input>
            </el-form-item>
            <!-- insuranceCost -->
            <el-form-item label="保险费" prop="insuranceCost">
              <el-input
                v-model="spendreimbursementform.insuranceCost"
              ></el-input>
            </el-form-item>
            <!-- otherCost -->
            <el-form-item label="其他费用" prop="otherCost">
              <el-input v-model="spendreimbursementform.otherCost"></el-input>
            </el-form-item>
          </div>
        </el-col>
        <!-- 第三列表单 -->
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <!-- applyTotalAmountLarge -->
            <el-form-item
              label="申报总金额(大写)"
              prop="applyTotalAmountLarge"
              label-width="140"
            >
              <el-input
                disabled
                v-model="spendreimbursementform.applyTotalAmountLarge"
              ></el-input>
            </el-form-item>
            <!-- applyTotalAmountSmall -->
            <el-form-item
              label="申报总金额(小写)"
              prop="applyTotalAmountSmall"
              label-width="140"
            >
              <el-input
                v-model="spendreimbursementform.applyTotalAmountSmall"
                @change="
                  convertCurrency(spendreimbursementform.applyTotalAmountSmall)
                "
              ></el-input>
            </el-form-item>
            <el-form-item
              label="出差时间"
              prop="startTime"
              required
              :rules="[
                {
                  required: true,
                  message: '请选择日期',
                  trigger: 'change',
                },
              ]"
            >
              <el-date-picker
                v-model="timeSlot"
                @change="formtime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <!-- nobillExplain -->
            <el-form-item label="无票据说明" prop="nobillExplain">
              <el-input
                v-model="spendreimbursementform.nobillExplain"
              ></el-input>
            </el-form-item>

            <el-form-item label="发票号码" prop="fromList">
              <el-select
                v-model="spendreimbursementform.fromList"
                multiple
                filterable
              
                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>

            <!-- remarks -->
            <el-form-item label="备注" prop="remarks">
              <el-input
                type="textarea"
                :rows="5"
                v-model="spendreimbursementform.remarks"
              ></el-input>
            </el-form-item>
          </div>
        </el-col>
        <!-- 第四列表单 -->
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <!-- 其他 -->
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-circle-plus"
                @click="addBtn1"
                >随行人员</el-button
              >
            </el-form-item>
            <!-- 对话框1 -->
            <el-dialog title="选择随行人员" :visible.sync="dialogFormVisible">
              <!--  -->
              <el-form :model="peopleList">
                <el-row
                  v-for="(item, index) in peopleList.insertBatch"
                  :key="index"
                >
                  <el-form-item
                    :label="'姓名' + (index + 1)"
                    :prop="'insertBatch.' + index + '.personnelName'"
                    :rules="{
                      required: true,
                      message: '姓名不能为空',
                      trigger: 'blur',
                    }"
                  >
                    <el-col :span="8"
                      ><div class="grid-content bg-purple-light">
                        <el-input
                          v-model.trim="item.personnelName"
                        ></el-input></div
                    ></el-col>
                    <el-col :span="3"
                      ><div class="grid-content bg-purple">
                        <el-button
                          style="margin-left: 5px"
                          :disabled="deletestaus"
                          @click.prevent="removeDomain(item)"
                          >删除</el-button
                        >
                      </div></el-col
                    >
                    <el-col :span="6"
                      ><div class="grid-content bg-purple-light">
                        <el-button @click="addDomain">新增人员</el-button>
                      </div></el-col
                    >
                  </el-form-item>
                </el-row>
              </el-form>
              <!--  -->
              <!-- 操作 -->
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false"
                  >确 定</el-button
                >
              </div>
            </el-dialog>
          </div>
        </el-col>
      </el-row>
    </el-main>
    <el-footer>
      <el-button type="primary" @click="submitForm()">提交</el-button>
      <el-button @click="resetForm()">重置</el-button>
      <el-button @click="back()">返回</el-button>
    </el-footer>
  </el-form>
</template>

<script>
import { insert } from "@/api/spendreimbursement.js";
import { selectTypeitem } from "@/api/spendreimbursement.js";
// selectProjectitem
import { selectProjectitem } from "@/api/spendreimbursement.js";
//selectProjectpeople
import { selectProjectpeople } from "@/api/spendreimbursement.js";
// insertId
import { insertId } from "@/api/spendreimbursement.js";
import { Addinvoice } from "@/api/spendreimbursement.js";
import { selectAllBystatus } from "@/api/project";
import { money } from "@/utils/myValidate";
export default {
  created() {
    this.Typeitem.companyId = this.$store.getters.companyId;
    this.Projectitem.companyId = this.$store.getters.companyId;
    this.Projectpeople.companyId = this.$store.getters.companyId;
    this.spendreimbursementform.companyId = this.$store.getters.companyId;
    this.spendreimbursementform.userId = this.$store.getters.urId;
    this.Selectinsertlsit();
    this.reimebursementtypeItem();
    this.reimebursementprojectItem();
    this.reimebursementprojectpeopleItem();
  },
  data() {
    return {
      dialogFormVisible: false,
      labelPosition: "left",
      values: false,
      timeSlot: null,
      userId: [],
      // fromList: [], //发票号码
      form: [],
      // 收集的是页面表单的数据
      spendreimbursementform: {
        fromList: [],
        companyId: null,
        summary: "",
        enclosureNumber: "",
        tripReason: "",
        typeId: "",
        fromPlace: "",
        remarks: "",
        purposePlace: "",
        transitPlace: "",
        startTime: "",
        endTime: "",
        applyTime: "",
        receiveSubsidy: 0,
        vehicle: "",
        foodAllowance: 0,
        publicMiscellaneousSubsidy: 0,
        tripCost: 0,
        planeTicket: 0,
        trafficCost: 0,
        lodgingCost: 0,
        insuranceCost: 0,
        otherCost: 0,
        remarks: "",
        nobillExplain: "",
        applyTotalAmountLarge: "",
        applyTotalAmountSmall: null,
        projectId: "",
        companyId: null,
        // 天数
        days: null,
        userId: null,
        tripStatus: 0,
      },
      peopleList: {
        insertBatch: [
          {
            personnelName: null,
            tripId: null,
          },
        ],
      },
      // 报销类型
      Typeitem: {
        companyId: null,
        typeCategory: 0,
      },
      // 项目类型
      Projectitem: {
        companyId: null,
      },
      // 随从成员
      Projectpeople: {
        companyId: null,
      },
      peopletripid: null,
      // 收集报销类型进行展示
      collectType: [],
      // 收集项目名称进行展示
      collectProject: [],
      // 收集随从人员进行展示
      collectProjectpeople: [],
      getinvoivelist: [],
      deletestaus: true,
      // 验证规则
      rules: {
        fromList: [
          { required: true, message: "此项不能为空！", trigger: "change" },
        ],
        summary: [{ required: true, message: "此项不能为空！" }],
        enclosureNumber: [
          { required: true, message: "此项不能为空！" },
          { type: "number", message: "格式不正确！" },
        ],
        tripReason: [{ required: true, message: "此项不能为空！" }],
        typeId: [
          {
            required: true,
            message: "此项不能为空！",
            trigger: "change",
          },
        ],

        fromPlace: [{ required: true, message: "此项不能为空！" }],
        purposePlace: [{ required: true, message: "此项不能为空！" }],
        transitPlace: [{ required: true, message: "此项不能为空！" }],
        applyTotalAmountLarge: [{ required: true, message: "此项不能为空！" }],
        applyTotalAmountSmall: [
          { validator: money, trigger: "blur" },
        ],
        applyTime: [
          {
            required: true,
            message: "请选择日期！",
            trigger: "change",
          },
        ],
        planeTicket: [{ required: true, message: "此项不能为空！" }],
        vehicle: [{ required: true, message: "此项不能为空！" }],
        foodAllowance: [
          { validator: money, trigger: "blur" },
        ],
        publicMiscellaneousSubsidy: [
          { validator: money, trigger: "blur" },
        ],
        tripCost: [
          { validator: money, trigger: "blur" },
        ],
        planeTicket: [
          { validator: money, trigger: "blur" },
        ],
        trafficCost: [
          { validator: money, trigger: "blur" },
        ],
        lodgingCost: [
          { validator: money, trigger: "blur" },
        ],
        insuranceCost: [
          { validator: money, trigger: "blur" },
        ],
        otherCost: [
          { validator: money, trigger: "blur" },
        ],

        remarks: [{ required: true, message: "此项不能为空！" }],
        projectId: [
          {
            required: true,
            message: "此项不能为空！",
            trigger: "change",
          },
        ],
        startTime: [{ required: true, message: "此项不能为空！" }],
        endTime: [{ required: true, message: "此项不能为空！" }],
        trafficCost: [{ required: true, message: "此项不能为空！" }],
        lodgingCost: [{ required: true, message: "此项不能为空！" }],
        insuranceCost: [{ required: true, message: "此项不能为空！" }],
        otherCost: [{ required: true, message: "此项不能为空！" }],
        nobillExplain: [{ required: true, message: "此项不能为空！" }],
      },
    };
  },
  methods: {
    //查询发票编号
    Selectinsertlsit() {
      let param = {
        companyId: this.$store.getters.companyId,
        status: 0,
        type: 2,
        userId: this.$store.getters.info.userId,
      };
      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();
        });
    },
    // 添加数据的方法
    submitForm() {
      this.$refs.ruleform.validate((valid) => {
        if (valid) {
          insert(this.spendreimbursementform)
            .then((res) => {
              if (res.success) {
                let tid = res.data;
                let addpeopleList = [];
                let obj1 = {};
                obj1.personnelName = this.$store.getters.name;
                obj1.tripId = tid;

                this.peopleList.insertBatch.forEach((e) => {
                  let obj = {};
                  obj.personnelName = e.personnelName;
                  addpeopleList.push(obj1, obj);
                });

                // 第二个方法 添加随从人员
                insertId(addpeopleList)
                  .then((result) => {
                    if (result.success) {
                      // 添加成功以后 把表单的数据清空
                      this.$refs.ruleform.resetFields();
                    } else {
                      this.$message.error(result.msg);
                    }
                  })
                  .catch((error) => {
                    this.$message.error("失败");
                  });
                this.spendreimbursementform.fromList.forEach((e) => {
                  let obj = {};
                  obj.companyId = this.$store.getters.companyId;
                  obj.status = 1;
                  obj.tripId = res.data;
                  obj.invoiceId = e;
                  this.form.push(obj);
                });
                // 第三个方法 添加发票
                Addinvoice(this.form)
                  .then((resu) => {
                    if (resu.success) {
                      this.$message.success("添加成功！");
                      this.back();
                    } else {
                      this.$message.error(resu.msg);
                    }
                  })
                  .catch((error) => {
                    this.$message.error("失败");
                  });
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((error) => {
              this.$message.error("添加失败");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //
    addDomain() {
      this.deletestaus = false;
      this.peopleList.insertBatch.push({
        personnelName: "",
        tripId: null,
      });
    },
    //
    removeDomain(item) {
      var index = this.peopleList.insertBatch.indexOf(item);
      if (index !== -1) {
        this.peopleList.insertBatch.splice(index, 1);
      }
    },
    // 报销类型
    reimebursementtypeItem() {
      selectTypeitem(this.Typeitem)
        .then((res) => {
          if (res.success) {
            this.collectType = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("查询失败");
        });
    },
    // 项目类型
    reimebursementprojectItem() {
      selectProjectitem(this.Projectitem)
        .then((res) => {
          if (res.success) {
            this.collectProject = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("查询失败");
        });
    },
    // 查询随从人员
    reimebursementprojectpeopleItem() {
      selectProjectpeople(this.Projectpeople)
        .then((res) => {
          if (res.code == 20000) {
            // console.log(res.data);
            this.collectProjectpeople = res.data;
          } else {
            this.$message.error("失败");
          }
        })
        .catch((error) => {
          this.$message.error("查询失败");
        });
    },
    // 弹窗按钮
    addBtn1() {
      this.peopleList.insertBatch = [0];
      this.deletestaus = true;
      this.dialogFormVisible = true;
    },
    // 开关选项
    changeswitch(values) {
      // console.log(values);
      if (values == true) {
        this.spendreimbursementform.receiveSubsidy = 1;
      } else {
        this.spendreimbursementform.receiveSubsidy = 0;
      }
    },
    // 返回上一级
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push("/spendreimbursementList");
    },
    //申请时间处理
    formtime3(val) {
      if (val != null) {
        let time = this.timestampToTime(val);
        this.spendreimbursementform.applyTime = time;
      }
    },
    // 计算天数
    DateDiff(sDate1, sDate2) {
      //sDate1和sDate2是2006-12-18格式
      var oDate1, oDate2, iDays;

      oDate1 = new Date(sDate1); //转换为12-18-2006格式

      oDate2 = new Date(sDate2);

      iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
      return iDays;
    },
    //开始结束 时间的处理  计算天数
    formtime(val) {
      if (val == null) {
        this.spendreimbursementform.startTime = null;
        this.spendreimbursementform.endTime = null;
      } else {
        this.spendreimbursementform.startTime = this.timestampToTime(val[0]);
        this.spendreimbursementform.endTime = this.timestampToTime(val[1]);
        let time = this.DateDiff(
          this.spendreimbursementform.startTime,
          this.spendreimbursementform.endTime
        );
        this.spendreimbursementform.days = time;
      }
    },
    //时间处理
    timestampToTime(value) {
      var date = value;
      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();
      return Y + M + D + h + m + s;
    },
    //重置
    resetForm() {
      this.$refs.ruleform.resetFields();
    },
    // 大小写
    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) {
        //超出最大处理数字
        this.$message.warning("你输入的数字太大了");
        return "";
      }
      if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast;
      }
      //转换为字符串，分离小数和整数部分
      money = money.toString();
      //00000
      if (money.indexOf(".") == -1) {
        //说明money是整数
        integerNum = money;
        decimalNum = "";
      } else {
        //说明money是小数
        //1.12   [1,12]
        parts = money.split(".");
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
      }

      //获取整型部分转换
      if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        //2222 4
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
          var n = integerNum.substr(i, 1);
          var p = IntLen - i - 1;
          //q是确定单位
          // 10000
          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.spendreimbursementform.applyTotalAmountLarge = chineseStr;
    },
  },
};
</script>

<style>
</style>