<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="报销总金额-大写" 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>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            :rows="5"
            placeholder="请输入内容"
            v-model="from.remarks"
          >
          </el-input>
        </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 type="primary" @click="drawerAdd()">申请报销单</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' }"
              >
                <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 v-show="subbut">
        <el-empty description="暂无报销项，因此无法报销"></el-empty>
      </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" border style="width: 90%">
          <el-table-column label="序号" width="50px">
            <template slot-scope="scope">
              {{
                (invoicegetQurey.pageNum - 1) * invoicegetQurey.pageSize +
                scope.$index +
                1
              }}
            </template>
          </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-page.sync="invoicegetQurey.pageNum"
          :page-size="invoicegetQurey.pageSize"
          @current-change="getincomeSelectlist"
          layout="total, prev, pager, next"
          :total="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="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="action"
              :auto-upload="false"
              :data="proutlist"
              :on-change="onChange"
              :on-remove="delfile2"
              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>
</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 { insert } from "@/api/reimbursement";
import { Details } from "@/api/reimbursement";
import {
  insertList,
  queryBypageIncomeAdd,
  selectAllBystatus,
} from "@/api/project";
import { updatesubmit, uploadFile } from "@/api/project";
export default {
  data() {
    return {
      //提交信息
      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
        // invoiceId: null, //发票的id
        fromList: [], //发票号码
        remarks: "", //备注
      },
      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" },
        ],
        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" },
        ],
      },

      //发票列表窗口
      drawer: false,
      isgetid: 0,
      //发票列表
      invoicegetList: [],
      //查询发票参数
      invoicegetQurey: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
      },
      total: 0,
      //添加发票的参数
      addTO: {
        userId: null,
        category: null,
        code: null,
        companyId: null,
        mone: null,
        number: null,
        status: 0, //发票是否已报销 0未报销 1已报销
        time: null,
        type: 2, // 0收入 1支出 2报销
      },
      //报销单区域
      options: [
        {
          value: 0,
          category: "普票",
        },
        {
          value: 1,
          category: "专票",
        },
      ],
      fileList: [], //发票图片存放位置
      action: null, //发票图片提交地址
      //图片提交携带的额外参数
      proutlist: {
        Id: null, //res.data
        status: 2, // 0代表收入 1代表收入 2代表日常报销 3代表出差报销
      },
      fileTypeJpg: false, //判断是否有发票文件且格式正确
    };
  },
  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.action = process.env.VUE_APP_BASE_API + "/file/uploadFile";
    this.time();
    this.getProject();
    this.getReimbursement();
    this.Selectinsertlsit();
  },
  methods: {
    //提交
    submitForm() {
      this.$refs.form.validate((valid1) => {
        if (valid1) {
          this.$refs.details.validate((valid) => {
            if (valid) {
              insert(this.from)
                .then((res) => {
                  if (res.success) {
                    //上传右边的报销项了 ，上传报销项之前，需要处理数据reimbursementId代表着本次提交报销表的id
                    this.reimbursementItemData.list.forEach((item) => {
                      item.reimbursementId = res.data;
                    });
                    Details(this.reimbursementItemData.list).then((res) => {
                      if (res.success) {
                        this.$message.success("申请成功，等待审批");
                        this.back();
                      } else {
                        this.$message.error(res.msg);
                      }
                    });
                    //上传发票号
                    let list = [];
                    this.from.fromList.forEach((item) => {
                      list.push({
                        invoiceId: item,
                        reimbursementId: res.data,
                        status: 1,
                      });
                    });
                    updatesubmit(list).then((res) => {
                      if (item.success) {
                        this.$messages.success("发票联邦成功");
                      } else {
                        this.$messages.error("发票联邦失败");
                      }
                    });
                  } else {
                    this.$message.error(res.msg);
                  }
                })
                .catch((error) => {
                  this.$message.error("提交失败");
                });
            }
          });
        }
      });
    },
    //重置信息
    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;
    },
    //返回
    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;
            // console.log(this.reimbursementItemList.length)
            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("金额格式错误"));
      }
    },

    //申请报销单
    drawerAdd() {
      this.drawer = true;
      this.getincomeSelectlist();
    },
    //查询发票
    getincomeSelectlist(pager = 1) {
      this.invoicegetQurey.pageNum = pager;
      queryBypageIncomeAdd(this.invoicegetQurey)
        .then((res) => {
          // console.log(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("查询发票数据失败");
        });
    },
    //添加报销单
    Reimbursement() {
      this.isgetid = 1;
    },
    //发票单区域
    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;
    },
    //发票提交
    getlistForm() {
      if (this.fileTypeJpg) {
        this.$refs.addTO.validate((valid) => {
          if (valid) {
            this.addTO.companyId = this.$store.getters.companyId;
            this.addTO.userId = this.$store.getters.info.userId;
            insertList(this.addTO)
              .then((res) => {
                console.log(res);
                console.log(this.isgetid);
                if (res.success) {
                  //上传图片
                  //res.data 是上传那图片参数之一
                  //上传前提参数要对  status id
                  this.proutlist.Id = res.data;
                  //el-uploda组件的提交方法
                  //vue ref //代表着给标签设立一个标识 <div id=""></div> 相当于id
                  //this.$refs   document.getElementById()
                  //手动上传
                  this.$refs.upload.submit();
                  this.$message.success(res.msg);
                  //切换到表格区域
                  this.isgetid = 0;
                  //初始化表单
                  this.addTO = {
                    userId: null,
                    category: null,
                    code: null,
                    companyId: null,
                    mone: null,
                    number: null,
                    status: 0,
                    time: null,
                    type: 2,
                  };
                  this.getincomeSelectlist();
                  this.Selectinsertlsit();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((error) => {
                console.log(error);
                this.$message.error("新建失败");
              });
          }
        });
      } else {
        this.$message.warning("需要发票的图片或文件");
      }
    },
    //取消
    cancel() {
      this.isgetid = 0;
      this.getincomeSelectlist();
    },
    //校验发票图片是否合格
    onChange(file) {
      const fileNamepdf = file.name;
      let fileType = fileNamepdf.substring(fileNamepdf.lastIndexOf("."));
      if (fileType == ".pdf" || fileType == ".png" || fileType == ".jpg") {
        this.fileTypeJpg = true;
      } else {
        this.fileTypeJpg = false;
        this.$message.warning("发票文件只能是pdf,png,jpg格式文件");
        this.$refs.upload.clearFiles();
      }
    },
    //清除发片文件
    delfile2(file, fileList) {
      this.fileTypeJpg = false;
    },
    //查询发票编号
    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();
        });
    },
  },
};
</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>