<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="typeId">
          <el-select v-model="from.typeId" placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            >
            </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="报销总金额-大写" 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="submitForm()"
            >提交</el-button
          >
          <el-button
            type="info"
            icon="el-icon-refresh-left"
            @click="resetForm()"
            >重置信息</el-button
          >
          <el-button type="primary" @click="drawerAdd()">申请报销单</el-button>
          <el-button @click="back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-drawer
        title="发票单列表"
        :visible.sync="drawer"
        size="100%"
      >
        <!-- 表格区域 -->
        <div class="drawer" v-show="isgetid == 0" style="margin-left: 5%">
          <el-button
            type="primary"
            @click="Reimbursement()"
            style="margin: 20px 0px"
            >添加报销单</el-button
          >
          <el-table :data="invoicegetList.list" border style="width: 90%">
            <el-table-column
              prop="invoiceId"
              label="序号"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="number"
              label="发票号码"
              width="width"
            ></el-table-column>
            <el-table-column prop="code" label="发票代码"></el-table-column>
            <el-table-column prop="time" label="发票时间"></el-table-column>
            <el-table-column prop="category" label="发票类型">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.category == '0' ? 'info' : 'primary'"
                  >{{ scope.row.category == "0" ? "普票" : "专票" }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="type" label="发票类别">
              <template slot-scope="scope">
                <el-tag
                  :type="
                    scope.row.type == '0'
                      ? 'success'
                      : scope.row.type == '1'
                      ? 'danger'
                      : 'warning'
                  "
                  >{{
                    scope.row.type == "0"
                      ? "收入"
                      : scope.row.type == "1"
                      ? "支出"
                      : "报销"
                  }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="mone" label="发票金额"></el-table-column>
            <el-table-column prop="status" label="发票状态">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status == '0' ? 'info' : 'warning'">{{
                  scope.row.status == 0 ? "未报销" : "已报销"
                }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页-->
          <!-- total:总的条目数 -->
          <el-pagination
            style="margin: 0px auto"
            @current-change="getincomeSelectlist"
            layout="total, prev, pager, next"
            :total="invoicegetList.total"
          ></el-pagination>
        </div>
        <!-- 添加区域 -->
        <div class="getadd" v-show="isgetid == 1" style="margin-left: 5%">
          <el-row>
            <el-col :xl="8" :lg="10" :md="8" :sm="12" :xs="24">
              <el-form
                style="width: 100%; margin: 30px 0px"
                :model="addTO"
                :rules="rules"
                ref="addTO"
                label-width="80px"
                class="demo-ruleForm"
              >
                <el-form-item label="发票号码" prop="number">
                  <el-input
                    v-model="addTO.number"
                    oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                  ></el-input>
                </el-form-item>
                <el-form-item label="发票代码" prop="code">
                  <el-input v-model="addTO.code"></el-input>
                </el-form-item>
                <el-form-item label="发票时间" required>
                  <el-date-picker
                    v-model="addTO.time"
                    type="datetime"
                    placeholder="选择日期时间"
                    @change="timestampToTime1()"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="发票类型" prop="category">
                  <el-select v-model="addTO.category" placeholder="请选择">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.category"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="发票金额" prop="mone">
                  <el-input v-model="addTO.mone"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="success"
                    icon="el-icon-folder-checked"
                    @click="getlistForm()"
                    >立即创建</el-button
                  >
                  <el-button
                    type="info"
                    icon="el-icon-refresh"
                    @click="delectdd"
                    >重置信息</el-button
                  >
                  <el-button
                    type="primary"
                    icon="el-icon-refresh-left"
                    @click="cancel()"
                    >取消</el-button
                  >
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :xs="4" :sm="6" :md="8" :lg="10" :xl="11">
              <el-upload
                class="upload-demo"
                ref="upload"
                :file-list="fileList"
                action="http://192.168.10.109:7080/file/uploadFile"
                :auto-upload="false"
                :data="proutlist"
                style="margin-left: 90px"
              >
                <el-button
                  slot="trigger"
                  size="small"
                  type="primary"
                  style="margin-left: 20px; margin-top: 40px"
                  >选取文件</el-button
                >
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-col>
          </el-row>
        </div>
      </el-drawer>
    </div>
    <div class="spend">
      <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' }"
            >
              <el-input v-model="item.money"></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 { selectAllCompanyId } from "@/api/reimbursementItem";
import { money } from "@/utils/myValidate";
import { selectAll as projectSelectAll } from "@/api/project";
import { selectAll as typeSelectAll } from "@/api/type";
import { insert } from "@/api/reimbursement";
import { Details } from "@/api/reimbursement";
import {
  insertList,
  queryBypageIncomeAdd,
  selectAllBystatus,
} from "@/api/project";
import { updatesubmit } from "@/api/project";
export default {
  data() {
    return {
      company: {},
      timeNow: null,
      projectList: [],
      typeList: [], //类型列表
      invoiceList: [], //发票号码
      from: {
        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
        typeId: null, //报销类别id
        invoiceId: null, //发票的id
        fromList: [],//发票号码
      },
      reimbursementItemData: {
        list: [],
      },
      reimbursementItemList: [],
      //报销单区域
      options: [
        {
          value: 0,
          category: "普票",
        },
        {
          value: 1,
          category: "专票",
        },
      ],
      addTO: {
        category: null,
        code: null,
        companyId: null,
        mone: null,
        number: null,
        status: 0,
        time: null,
        type: 2,
      },
      isgetid: 0,
      //表单验证内容
      rules: {
        typeId: [
          { required: true, message: "请选择报销类别", trigger: "change" },
        ],
        invoiceId:[
          { required: true, message: "请选择发票号码", trigger: "change" },
        ],
        projectId: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        applyTotalAmountLarge: [
          {
            required: true,
            message: "请输入申请报销总金额（大写）",
            trigger: "blur",
          },
        ],
        applyTotalAmountSmall: [
          { required: true, validator: money, trigger: "blur" },
        ],
        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" },
        ],
      },
      //查询发票数据
      invoiceList: {
        category: null,
        code: null,
        companyId: null,
        invoiceId: null,
        mone: null,
        number: null,
        orders: [
          {
            asc: null,
            column: null,
          },
        ],
        pageNum: 1,
        pageSize: 10,
        searchCount: null,
        status: null,
        time: null,
        type: null,
      },
      drawer: false, //抽屉的显示与隐藏
      //发票状态
      status: 0,
      //发票的数组
      invoicegetList: [],
      //发票编号数组
      getinvoivelist: [],
      //收集发票编号
      invoiceListAdd: {},
      //查询发票编号的数组
      getinvoiveId: {
        companyId: null,
        type: 1,
      },
      pageNum: 10,
      total: 1,
      //收集数据
      newList: [],
      //保存图片
      proutlist: {
        Id: 1,
        status: 1,
      },
      fileList: [],

    };
  },
  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;
    //获取公司id
    this.invoiceList.companyId = this.$store.getters.companyId;
    this.from.companyId = this.$store.getters.companyId;
    this.addTO.companyId = this.$store.getters.companyId;
    this.time();
    this.getTypeList();
    this.getReimbursement();
    this.getProject();
    this.Selectinsertlsit(); //获取发票号码
  },
  methods: {
    //解决输入框无法输入
    change() {
      this.$forceUpdate();
    },

    //获取公司报销类别
    getTypeList() {
      let param = {
        companyId: this.$store.getters.companyId,
        //typeCategory: 2,
      };
      typeSelectAll(param)
        .then((res) => {
          if (res.success) {
            this.typeList = res.data;
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch((error) => {
          this.$message.error("获取类型失败");
          this.back();
        });
    },
    //获取个人的项目
    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) {
            //获取数据
            this.reimbursementItemList = res.data;

            //处理数据
            this.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("获取报销项失败");
        });
    },
    //获取公司名称
    getCompany() {
      selectById({ companyId: this.$store.getters.companyId })
        .then((res) => {
          if (res.status == "success") {
            this.company = res.data;
          } else {
            this.$message.error(res.data);
          }
        })
        .catch((error) => {
          this.$message.error("获取公司名称失败");
        });
    },
    //提交
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //如果左侧校验成功，则开始校验右侧
          this.$refs.details.validate((valid2) => {
            if (valid2) {
              insert(this.from)
                .then((res) => {
                  if (res.success) {
                    this.reimbursementItemData.list.forEach((item) => {
                      item.reimbursementId = res.data;
                    });
                    let list = [];
                    this.from.fromList.forEach((item) => {
                      list.push({
                        invoiceId: item,
                        reimbursementId: res.data,
                        status: 1,
                      });
                    });
                    updatesubmit(list)
                      .then((item) => {
                        if (item.success) {
                          Details(this.reimbursementItemData.list).then(
                            (res) => {
                              if (res.success) {
                                this.$message.success("申请成功，等待审批");
                                this.back();
                              }
                            }
                          );
                        }
                      })
                      .catch((error) => {
                        console.log("报销失败");
                      });
                  } else {
                    this.$message.error(res.msg);
                  }
                })
                .catch((error) => {
                  this.$message.error("申请失败");
                });
            } else {
              this.$message.error("请选择报销项");
            }
          });
        }
      });
    },
    //获取现在时间
    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;
      this.timeNow = Y + "年" + M + "月" + D + "日";
    },
    //新增消费
    consumption() {
      this.spend.push({});
    },
    //返回
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({ path: "/reimbursementList" });
    },
    //重置信息
    resetForm() {
      this.$refs.form.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;
    },
    //定义金额校验
    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("金额格式错误"));
      }
    },
    //发票单区域
    timestampToTime1() {
      var date = this.addTO.time;
      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.addTO.time = Y + M + D + h + m + s;
    },
    //发票页面的按钮事件
    drawerAdd() {
      this.drawer = true;
      this.getincomeSelectlist();
    },
    //发票的分页查询
    getincomeSelectlist(pager = 1) {
      this.invoiceList.pageNum = pager;
      queryBypageIncomeAdd(this.invoiceList)
        .then((res) => {
          // console.log(res)
          if (res.success) {
            this.invoicegetList = res.data;
            this.total = res.data.total;
          } else {
            this.$message.errror(res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("查询发票数据失败");
        });
    },
    //分页
    handleSizeChange(val) {
      this.invoicegetList.pageSize = pageSize;
    },
    handleCurrentChange(currentPage) {
      this.invoicegetList.pageNum = currentPage;
    },
    //取消隐藏tatle
    cancel() {
      // console.log(this.isgetid);
      this.isgetid = 0;
      this.getincomeSelectlist();
    },
    //显示报销单添加页面
    Reimbursement() {
      this.isgetid = 1;
    },
    //发票提交页面的提交
    getlistForm() {
      this.$refs.addTO.validate((valid) => {
        if (valid) {
          insertList(this.addTO)
            .then((res) => {
              if (res.success) {
                this.proutlist.Id = res.data;
                //提交图片
                this.$refs.upload.submit();
                this.$message.success(res.msg);
                this.isgetid = 0;
                this.addTO.time = "";
                this.$refs.addTO.resetFields();
                this.getincomeSelectlist();
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((error) => {
              this.$message.error("新建失败");
            });
        }
      });
    },
    //数据清除
    delectdd() {
      this.$refs.addTO.resetFields();
    },
    //查询发票编号
    Selectinsertlsit() {
      let param = {
        companyId: this.$store.getters.companyId,
        status: 0,
        type: 2,
      };
      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();
        });
    },
  },
};
</script>

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

<style scoped>

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