<template>
  <!-- 添加支出区域 -->
  <div class="container">
    <el-row>
      <el-col :xl="8" :lg="10" :md="8" :sm="12" :xs="24">
        <el-form ref="form" :model="expendFrom" label-width="120px" :rules="rules">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="expendFrom.projectName" disabled></el-input>
          </el-form-item>

          <el-form-item label="支出类别" prop="expendType">
            <el-select v-model="expendFrom.expendType" 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="incomebaoxioa">
            <el-select
              v-model="invoiceListAdd"
              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="expendMoney">
            <el-input v-model="expendFrom.expendMoney"></el-input>
          </el-form-item>

          <el-form-item label="支出时间" prop="expendTime">
            <el-date-picker
              v-model="expendFrom.expendTime"
              type="datetime"
              placeholder="选择日期时间"
              @change="timestampToTime()"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="支出对象" prop="expendObject">
            <el-input v-model="expendFrom.expendObject"></el-input>
          </el-form-item>

          <el-form-item label="支出内容" prop="expendBody">
            <el-input v-model="expendFrom.expendBody"></el-input>
          </el-form-item>

          <el-form-item label="支出备注" prop="expendRemarks">
            <el-input v-model="expendFrom.expendRemarks"></el-input>
          </el-form-item>

          <el-form-item label="支出详情" prop="expendInformation">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8 }"
              v-model="expendFrom.expendInformation"
            ></el-input>
          </el-form-item>
          <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>
      </el-col>

      <!-- 合同上传 -->
      <el-col :xl="8" :lg="10" :md="8" :sm="12" :xs="24" class="contract">
        <el-upload
          class="upload-demo"
          ref="upload1"
          :action="action2"
          :file-list="fileList"
          :auto-upload="false"
          :on-change="onChangepdf"
          :on-remove="delfile1"
          :limit="1"
          :data="proutlist1"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/pdf文件，且不超过500kb</div>
        </el-upload>
      </el-col>
    </el-row>
    <!-- 报销单 -->
    <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>
        <!-- 分页-->
        <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="action"
              :auto-upload="false"
              :data="proutlist"
              style="margin-left:90px;"
              :on-change="onChange"
              :on-remove="delfile2"
              :limit="1"
            >
              <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 {
  selectByProjectId,
  insertList,
  queryBypageIncomeAdd,
  selectAllBystatus,
  updatesubmit
} from "@/api/project";
import { selectAll } from "@/api/type";
import { insert } from "@/api/expend";
export default {
  data() {
    return {
      action2: null,
      action: null,
      expendFrom: {
        expendBody: null,
        expendInformation: null,
        expendMoney: null,
        expendObject: null,
        expendRemarks: null,
        expendTime: null,
        expendType: null,
        projectId: null,
        userId: null,
        projectName: null
      },
      typeList: [],
      projectData: {},
      rules: {
        projectName: [
          { required: true, message: "请选择项目", trigger: "change" }
        ],
        expendType: [
          { required: true, message: "请选择支出类型", trigger: "change" }
        ],
        expendMoney: [
          { required: true, message: "请输入支出金额", trigger: "blur" }
        ],
        expendTime: [
          { required: true, message: "请选择支出时间", trigger: "change" }
        ]
      },
      companyId: 0,
      isgetid: 0,
      drawer: false, //抽屉的显示与隐藏
      typeList: [],
      projectData: {},
      options: [
        {
          value: 0,
          category: "普票"
        },
        {
          value: 1,
          category: "专票"
        }
      ],
      //添加发票的数组
      addTO: {
        category: 0,
        code: null,
        companyId: null,
        mone: null,
        number: null,
        status: 0,
        time: null,
        type: 1,
        userId: null
      },
      //表单验证内容
      rules: {
        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
      },
      //发票状态
      status: 0,
      //发票的数组
      invoicegetList: [],
      //发票编号数组
      getinvoivelist: [],
      //收集发票编号
      invoiceListAdd: {},
      //查询发票编号的数组
      getinvoiveId: {
        userId: null,
        companyId: null,
        type: 1
      },
      pageNum: 10,
      total: 1,
      //收集数据
      newList: [],
      //保存图片
      proutlist: {
        Id: null,
        status: 1
      },
      //保存合同
      proutlist1: {
        Id: null,
        status: 1
      },
      fileList: [],
      fileType: null,
      fileTypepdf: false,
      backlistid: null
    };
  },
  computed: {
    projectId() {
      return this.$route.query.id;
    }
  },
  created() {
    this.expendFrom.userId = this.$store.getters.urId;
    this.addTO.companyId = this.$store.getters.companyId;
    this.addTO.userId = this.$store.getters.urId;
    this.invoiceList.companyId = this.$store.getters.companyId;
    this.getinvoiveId.companyId = this.$store.getters.companyId;
    this.getinvoiveId.userId = this.$store.getters.urId;
    this.action = process.env.VUE_APP_BASE_API + "/file/uploadFile";
    this.action2 =
      process.env.VUE_APP_BASE_API + "/file/updataContractDocuments";
    this.backlistid = this.$route.query.backlistid;
    this.getTypeList();
    this.getProject();
    this.Selectinsertlsit();
  },
  methods: {
    //获取支出类型
    getTypeList() {
      let param = {
        companyId: this.$store.getters.companyId,
        typeCategory: 1
      };
      selectAll(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() {
      let param = {
        projectId: this.projectId
      };
      selectByProjectId(param)
        .then(res => {
          if (res.success) {
            this.projectData = res.data;
            this.expendFrom.projectName = res.data.projectName;
            this.expendFrom.projectId = res.data.projectId;
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch(error => {
          this.$message.error("获取项目失败");
          this.back();
        });
    },
    //提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          insert(this.expendFrom)
            .then(res => {
              if (res.success) {
                this.$message.success(res.msg);
                console.log(this.fileTypepdf);
                if (this.fileTypepdf) {
                  //进行合同的上传
                  //上传合同
                  this.proutlist1.Id = res.data;
                  console.log(this.proutlist1.Id);

                  this.$refs.upload1.submit();
                }
                if (this.invoiceListAdd.length > 0) {
                  let list = [];
                  this.invoiceListAdd.forEach(item => {
                    list.push({
                      invoiceId: item,
                      expendId: res.data,
                      status: 1
                    });
                  });
                  //上传发票记录
                  updatesubmit(list).then(res => {
                    if (res.success) {
                      this.$message.success(res.msg);
                      this.back();
                    } else {
                      this.$message.error(res.msg);
                    }
                  });
                } else {
                  this.back();
                }
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch(error => {
              this.$message.error("新建失败");
            });
        }
      });
    },
    //重置
    resetForm() {
      this.$refs.form.resetFields();
      this.expendFrom.projectName = this.projectData.projectName;
      this.expendFrom.projectId = this.projectData.projectId;
    },
    //返回
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        path: "/expendList",
        query: {
          id: this.$route.query.id,
          backlistid: this.$route.query.backlistid
        }
      });
    },
    //时间处理 yyyy-MM-dd hh:mm:ss
    timestampToTime() {
      var date = this.expendFrom.expendTime;
      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.expendFrom.expendTime = Y + M + D + h + m + s;
    },
    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;
    },
    //合同图片
    onChangepdf(file) {
      const fileNamepdf = file.name;
      let fileType = fileNamepdf.substring(fileNamepdf.lastIndexOf("."));
      if (fileType == ".pdf") {
        this.fileTypepdf = true;
      } else {
        this.$message.warning("合同文件只能是pdf格式文件");
        this.$resf.upload1.clearFiles();
        this.fileTypepdf = false;
      }
      console.log(this.fileTypepdf);
    },
    //清楚合同文件
    delfile1() {
      this.fileTypepdf = false;
    },
    //清除发片文件
    delfile2() {
      this.fileTypeJpg = false;
    },
    //////发票区域//////

    //发票页面的按钮事件
    drawerAdd() {
      this.drawer = true;
      this.getincomeSelectlist();
    },
    //发票的分页查询
    getincomeSelectlist(pager = 1) {
      this.invoiceList.pageNum = pager;
      queryBypageIncomeAdd(this.invoiceList)
        .then(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) {
          if (
            this.fileType === ".jpg" ||
            this.fileType === ".pdf" ||
            this.fileType === ".png"
          ) {
            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();
                  this.Selectinsertlsit();
                  this.getincomeSelectlist();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch(error => {
                this.$message.error("新建失败");
              });
          } else {
            this.$message.error("请输入jpg格式的图片或者pdf在或者png的文件");
          }
        }
      });
    },
    //数据清除
    delectdd() {
      this.addTO = {
        category: 0,
        code: null,
        companyId: null,
        mone: null,
        number: null,
        status: 0,
        time: null,
        type: 1
      };
    },
    //查询发票编号
    Selectinsertlsit() {
      selectAllBystatus(this.getinvoiveId)
        .then(res => {
          if (res.success) {
            this.getinvoivelist = res.data;
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch(error => {
          this.$message.error("获取发票编号失败");
          this.back();
        });
    },
    //给fileType赋值
    onChange(file) {
      const fileName = file.name;
      this.fileType = fileName.substring(fileName.lastIndexOf("."));
      console.log(this.fileType);
    }
  }
};
</script>

<style scoped>
.container {
  padding: 10px;
}
.contract {
  margin: 20px 50px;
}
</style>