<template>
  <el-form
    ref="ruleform"
    :model="spendreimbursementform"
    label-width="120px"
    :label-position="labelPosition"
    :rules="rules"
    :data="spendreimbursementform"
  >
    <el-main>
      <el-row :gutter="20">
        <!-- 第一列表单 -->
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <!-- projectId -->
            <el-form-item
              label="报销项目"
              :label-width="formLabelWidth"
              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"
                value=""
              ></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: 'blur',
                },
              ]"
            >
              <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>
            <!-- 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-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 { selectTypeitem } from "@/api/spendreimbursement.js";
import { insertId } from "@/api/spendreimbursement.js";
// selectProjectitem
import { selectProjectitem } from "@/api/spendreimbursement.js";
import { update } from "@/api/spendreimbursement.js";
import { selectByTripId } from "@/api/spendreimbursement.js";
export default {
  created() {
    this.triplistfrom();
    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.reimebursementtypeItem();
    this.reimebursementprojectItem();
    this.reimebursementprojectpeopleItem();
  },
  data() {
    var 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("金额格式错误"));
      }
    };
    return {
      dialogFormVisible: false,
      labelPosition: "left",
      values: false,
      timeSlot: [],
      userId: [],
      // 收集的是页面表单的数据
      spendreimbursementform: {
        companyId: null,
        summary: "",
        enclosureNumber: "",
        tripReason: "",
        typeId: "",
        fromPlace: "",
        remarks: "",
        purposePlace: "",
        transitPlace: "",
        startTime: "",
        endTime: "",
        applyTime: "",
        receiveSubsidy: 0,
        vehicle: "",
        foodAllowance: "",
        publicMiscellaneousSubsidy: "",
        tripCost: "",
        planeTicket: "",
        trafficCost: "",
        lodgingCost: "",
        insuranceCost: "",
        otherCost: "",
        remarks: "",
        nobillExplain: "",
        applyTotalAmountLarge: "",
        applyTotalAmountSmall: "",
        projectId: "",
        companyId: null,
        // 天数
        days: null,
        userId: null,
        tripStatus: 0,
      },
      peopleId: [],
      insertBatch: [
        {
          personnelId: null,
          tripId: null,
        },
      ],
      // 报销类型
      Typeitem: {
        companyId: null,
        typeCategory: 0,
      },
      // 项目类型
      Projectitem: {
        companyId: null,
      },
      // 随从成员
      Projectpeople: {
        companyId: null,
      },
      // 收集报销类型进行展示
      collectType: [],
      // 收集项目名称进行展示时间
      collectProject: [],
      // 验证规则
      rules: {
        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: [
          { required: true, message: "此项不能为空！" },
          { validator: moneyrow, trigger: "blur" },
        ],
        applyTime: [
          {
            required: true,
            message: "请选择日期！",
            trigger: "change",
          },
        ],
        planeTicket: [{ required: true, message: "此项不能为空！" }],
        vehicle: [{ required: true, message: "此项不能为空！" }],
        foodAllowance: [
          { required: true, message: "此项不能为空！" },
          { validator: moneyrow, trigger: "blur" },
        ],
        publicMiscellaneousSubsidy: [
          { required: true, message: "此项不能为空！" },
          { validator: moneyrow, trigger: "blur" },
        ],
        tripCost: [
          { required: true, message: "此项不能为空！" },
          { validator: moneyrow, trigger: "blur" },
        ],
        planeTicket: [
          { required: true, message: "此项不能为空！" },
          { validator: moneyrow, trigger: "blur" },
        ],
        trafficCost: [
          { required: true, message: "此项不能为空！" },
          { validator: moneyrow, trigger: "blur" },
        ],
        lodgingCost: [
          { required: true, message: "此项不能为空！" },
          { validator: moneyrow, trigger: "blur" },
        ],
        insuranceCost: [
          { required: true, message: "此项不能为空！" },
          { validator: moneyrow, trigger: "blur" },
        ],
        otherCost: [
          { required: true, message: "此项不能为空！" },
          { validator: moneyrow, 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: "此项不能为空！" }],
      },
    };
  },
  computed: {
    reimbursementId() {
      return this.$route.query.tripid;
    },
  },
  methods: {
    // 查看详情
    triplistfrom() {
      selectByTripId({
        tripId: this.$route.query.tripid,
      })
        .then((res) => {
          if (res.success) {
            //获取数据(把data里的数据放在数组里面)
            this.spendreimbursementform = res.data;
            if (res.data.receiveSubsidy == 1) {
              this.values = true;
            } else {
              this.values = false;
            }
            this.timeSlot = [];
            this.timeSlot.push(res.data.startTime);
            this.timeSlot.push(res.data.endTime);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("获取失败");
        });
    },
    // 修改数据的方法
    submitForm() {
      this.$refs.ruleform.validate((valid) => {
        if (valid) {
          update(this.spendreimbursementform)
            .then((res) => {
              if (res.success) {
                this.$message.success("修改成功！");
                this.$router.push("/spendreimbursementList");
              }
            })
            .catch((error) => {
              this.$message.error("修改失败");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 报销类型
    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("查询失败");
        });
    },
    // 开关选项
    changeswitch(values) {
      // console.log(values);
      if (values == true) {
        this.spendreimbursementform.receiveSubsidy = 1;

      } else {
        this.spendreimbursementform.receiveSubsidy = 0;
        this.spendreimbursementform.foodAllowance = 0;
        this.spendreimbursementform.publicMiscellaneousSubsidy = 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 aDate, oDate1, oDate2, iDays;
      aDate = sDate1.split("-");
      oDate1 = new Date(aDate[1] + "-" + aDate[2] + "-" + aDate[0]); //转换为12-18-2006格式
      aDate = sDate2.split("-");
      oDate2 = new Date(aDate[1] + "-" + aDate[2] + "-" + aDate[0]);
      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) {
      console.log(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();
      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.spendreimbursementform.applyTotalAmountLarge = chineseStr;
    },
  },
};
</script>
  
  <style>
</style>