<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="summary">
            <el-input v-model="from.summary"></el-input>
          </el-form-item>    
         
          <el-form-item label="报销总金额-大写(元)" prop="applyTotalAmountLarge">
            <el-input v-model="from.applyTotalAmountLarge" ></el-input>
          </el-form-item>
          <el-form-item label="报销总金额-小写(元)" prop="applyTotalAmountSmall">
            <el-input v-model="from.applyTotalAmountSmall" ></el-input>
          </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>
        
    </div>
    <div class="spend">
      <el-form
      :model="reimbursementItemData"
      :inline="true"
      ref="details"
      label-width="150px">
          <el-row
            v-for="(item, index) in reimbursementItemData.list"
            :key="index"
          >
            <el-col>
              <el-form-item
                :label="item.name"
                :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>
</template>

<script>
import { selectById } from "@/api/company";
import {selectById as reimbursementSelectById,update} from "@/api/reimbursement"
import {money} from "@/utils/myValidate";
import { selectAll as projectSelectAll } from "@/api/project";
import { selectByReimbursementId } from "@/api/reimbursementDetails";
import { update as detailsUpdate } from "@/api/reimbursementDetails";
import {
  insertList,
  queryBypageIncomeAdd,
  selectAllBystatus,
} from "@/api/project";
export default {
  data() {
    return {
     
      reimbursementItemData: {
        list: [],
      },
      reimbursementItemList:[],
      company:{},
      timeNow:null,
      projectList:[],
      typeList:[],
      from:{
        userName:null,//申报人
        userPhone:null,//联系电话
        userId:null,//申报人Id
        officeExpenses:0,//办公费
        printingFee:0,//版面复印打印费
        consultingFee:0,//咨询费
        serviceCharge:0,//手续费
        postage:0,//邮电费
        trafficExpense:0,//交通费
        maintenanceCost:0,//维修（护）费
        rentalFee:0,//租赁费
        conferenceExpenses:0,//会议费
        trainingFee:0,//培训费
        entertainmentExpenses:0,//招待费
        specialMaterialCost:0,//专用材料费
        serviceFee:0,//劳务费
        travelExpenses:0,//差旅费
        other:0,//其他
        entrustedBusinessFee:0,//委托业务费
        summary:null,//摘要
        enclosureNumber:0,//附件数量
        fillingTime:null,//填报日期
        applyTotalAmountLarge:null,//申请报销总金额（大写）
        applyTotalAmountSmall:null,//申请报销总金额（小写）
        paymentMethod:null,//支付方式
        reimbursementState:0,//状态
        projectId:null,//项目id
        typeId:null,//报销类别id
        invoiceId:null,
        money: "",//备注
      },
      //发票编号数组
      getinvoivelist: [],
      rules:{
        typeId:[
          { required: true, message: '请选择报销类别', trigger: 'change'}
        ],
        projectId:[
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        applyTotalAmountLarge:[
           { required: true, message: "请输入申请报销总金额（大写）", trigger: "blur" },
        ],
        applyTotalAmountSmall:[
           { required: true, message: "请输入申请报销总金额（小写）", trigger: "blur" },
        ],
        entrustedBusinessFee:[
          { validator:money, trigger: "blur" },
        ],
        other:[
          { validator:money, trigger: "blur" },
        ],
        travelExpenses:[
          { validator:money, trigger: "blur" },
        ],
        serviceFee:[
          { validator:money, trigger: "blur" },
        ],
        specialMaterialCost:[
          { validator:money, trigger: "blur" },
        ],
        entertainmentExpenses:[
          { validator:money, trigger: "blur" },
        ],
        trainingFee:[
          { validator:money, trigger: "blur" },
        ],
        conferenceExpenses:[
          { validator:money, trigger: "blur" },
        ],
        rentalFee:[
          { validator:money, trigger: "blur" },
        ],
        maintenanceCost:[
          { validator:money, trigger: "blur" },
        ],
        trafficExpense:[
          { validator:money, trigger: "blur" },
        ],
        postage:[
          { validator:money, trigger: "blur" },
        ],
        serviceCharge:[
          { validator:money, trigger: "blur" },
        ],
        consultingFee:[
          { validator:money, trigger: "blur" },
        ],
        printingFee:[
          { validator:money, trigger: "blur" },
        ],
        officeExpenses:[
          { validator:money, trigger: "blur" },
        ],
      }
    };
  },
  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.getFrom()
    // this.getTypeList()
    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) {
            //获取数据(把data里的数据放在数组里面)
            this.reimbursementItemData.list=res.data
            //[{name:'办公费用'，money:18},{name:'办公费用'，money:18}]
          } 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.from.money=this.$route.query.money
    this.getReimbursement() 
    },
    //获取个人的项目
    getProject(){
      projectSelectAll({userId:this.from.userId}).then((res)=>{
       
        if(res.success){
          // console.log(res.data)
          this.projectList = res.data
        }else{
          this.$message.error(res.msg)
        }
      }).catch((error)=>{
        this.$message.error("获取个人项目失败，无法申请报销")
      })
    },
    //获取公司名称
    getCompany() {
      selectById({ companyId: this.$store.getters.companyId })
        .then((res) => {
          if (res.status == "success") {
            // console.log(res.data)
            this.company = res.data;
          } else {
            this.$message.error(res.data);
          }
        })
        .catch((error) => {
          this.$message.error("获取公司名称失败");
        });
    },
    //打印
    billPrintClick() {
      const style = "@page {margin:0 10mm};"; 
      printJS({
        printable: "printBill", 
        type: "html",
        headerStyle: "font-size:22px;text-align: center;",
        header: this.company.companyName + "日常报销单",
        ignoreElements:['caption','button'],
        targetStyles: ["*"],
        style,
      });
    },
    //修改
    updateForm(){
      //金额的校验
      this.$refs.form.validate((valid)=>{
        if(valid){//第一次校验左边
          this.$refs.details.validate(valid2=>{
          if(valid2){ 
            update(this.from).then((res)=>{
            if(res.success){
              
              detailsUpdate(this.reimbursementItemData.list).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()
    },
      //定义金额校验
      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("金额格式错误"));
      }
    },
     //查询发票编号
     Selectinsertlsit() {
      let param = {
        companyId: this.$store.getters.companyId,
        status: 0,
        type: 2,
        userId:this.$store.getters.info.userId,
      };
      console.log(this.$store.getters.companyId)
      selectAllBystatus(param)
        .then((res) => {
          // console.log(res)
          if (res.success) {
            this.getinvoivelist = res.data;
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch((error) => {
          this.$message.error("获取发票编号失败");
          this.back();
        });
    },
      //定义金额校验
      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("金额格式错误"));
      }
    },
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
}
</style>

<style scoped>
.clearfloat:after {
  /*伪元素是行内元素 正常浏览器清除浮动方法*/
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.no-border {
  border: none;
}
.show-border {
  border: 1px solid black;
}
.printTable {
  float: left;
  width: 794px;
  height: 1123px;
  padding: 20px 80px;
  box-sizing: border-box;
  font-size: 14px;
}
.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: 800px;
  float: left;
  margin: 60px 0px;
  padding: 20px 10px;
  /* box-sizing: border-box;
  border:1px #000 solid; */
  border-radius: 30px;
}
.spend {
  width: 800px;
  float: left;
  margin: 60px 0px;
  padding: 20px 10px;
}
</style>