<template>
  <div class="container">
    <el-row :gutter="20">
      <el-col :xl="8" :lg="10" :md="8" :sm="12" :xs="24">
        <el-form ref="form" :model="incomeFrom" label-width="120px" :rules="rules">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="incomeFrom.projectName" disabled></el-input>
          </el-form-item>
          <el-form-item label="收入类别" prop="incomeType">
            <el-select v-model="incomeFrom.incomeType" 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="incomeMoney">
            <el-input v-model="incomeFrom.incomeMoney"></el-input>
          </el-form-item>
          <el-form-item label="收到时间" prop="incomeTime">
            <el-date-picker
              v-model="incomeFrom.incomeTime"
              type="datetime"
              placeholder="选择日期时间"
              @change="timestampToTime()"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="对方户名" prop="incomeObject">
            <el-input v-model="incomeFrom.incomeObject"></el-input>
          </el-form-item>
          <el-form-item label="收入内容" prop="incomeBody">
            <el-input v-model="incomeFrom.incomeBody"></el-input>
          </el-form-item>
          <el-form-item label="收入备注" prop="incomeRemarks">
            <el-input v-model="incomeFrom.incomeRemarks"></el-input>
          </el-form-item>
          <el-form-item label="收入详情" prop="incomeInformation">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8 }"
              v-model="incomeFrom.incomeInformation"
            ></el-input>
          </el-form-item>
          <el-form-item></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="action1"
          :on-change="onChangepdf"
          :file-list="fileList1"
          :on-remove="delfile1"
          :auto-upload="false"
          :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-col :span="24">
        <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-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 label="序号" width="80px">
            <template slot-scope="scope">
              {{
              (invoicegetList.qurey.pageNum - 1) * invoicegetList.qurey.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>
        <!-- 分页 -->
        <el-pagination
          style="margin:0px auto"
          :current-page.sync="invoicegetList.qurey.pageNum"
          :page-size="invoicegetList.qurey.pageSize"
          @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="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="upload2"
              :file-list="fileList2"
              :action="action2"
              :auto-upload="false"
              :data="proutlist2"
              :on-change="onChange"
              :on-remove="delfile2"
              :limit="1"
              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 {
  selectByProjectId,
  insertList,
  queryBypageIncomeAdd,
  selectAllBystatus,
  updatesubmit
} from "@/api/project";
import { selectAll } from "@/api/type";
import { insert } from "@/api/imcome";

export default {
  data() {
    return {
      //表单
      incomeFrom: {
        incomeBody: null,
        incomeInformation: null,
        incomeMoney: null,
        incomeObject: null,
        incomeRemarks: null,
        incomeTime: null,
        incomeType: null,
        projectId: null,
        userId: null,
        projectName: null,
        incomebaoxioa: null //报销的字段
      },
      rules: {
        projectName: [
          { required: true, message: "请选择项目", trigger: "change" }
        ],
        incomeType: [
          { required: true, message: "请选择收入类型", trigger: "change" }
        ],
        incomeMoney: [
          { required: true, message: "请输入收入金额", trigger: "blur" }
        ],
        incomeTime: [
          { required: true, message: "请选择收入时间", trigger: "change" }
        ],
                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" }]
      },
      options: [
        {
          value: 0,
          category: "普票"
        },
        {
          value: 1,
          category: "专票"
        }
      ],
      invoiceListAdd: [], //选择的发票号
      getinvoivelist: [], //查询的能选择的表单信息
      typeList: [], //收入类型列表
      fileTypepdf: false, //判断合同文件是否存在
      fileList1: [], //合同文件
      //合同文件上传携带参数
      proutlist1: {
        Id: null,
        status: 0 //0收入 1支出
      },
      drawer: false, //发票视图
      isgetid: 0, //发票视图切换
      //发票参数
      invoicegetList: {
        list: [], //发票列表
        //查询发票条件
        qurey: {
          pageNum: 1,
          pageSize: 5,
          companyId: null
        },
        total: 0
      },
      //添加发票的参数
      addTO: {
        category: 0, //0收入 1支出 2报销
        code: null,
        companyId: null,
        mone: null,
        number: null,
        status: 0,//状态 0未报销 1已报销
        time: null,
        type: 0,//0 普票 1专票
        userId: null //提交人
      },
      //发票类型
      options: [
        {
          value: 0,
          category: "普票"
        },
        {
          value: 1,
          category: "专票"
        }
      ],
      //判断发票文件是否存在
      fileTypeJpg:false,
      fileList2: [], //发票文件
      proutlist2: {
        Id: null,
        status: 0 //0收入 1支出
      },
      //查询发票编号的参数
      getinvoiveId: {
        userId: null,
        companyId: null,
        type: 0
      },
    };
  },
  computed: {
    projectId() {
      return this.$route.query.id;
    }
  },
  created() {
    //用户id
    this.incomeFrom.userId = this.$store.getters.urId;

    this.invoicegetList.qurey.companyId = this.$store.getters.companyId;
    
    //发票上传地址
    this.action2 = process.env.VUE_APP_BASE_API + "/file/uploadFile";
    //合同上传地址
    this.action1 = process.env.VUE_APP_BASE_API + "/file/updataContractDocuments";

    this.getinvoiveId.userId = this.$store.getters.urId;
    this.getinvoiveId.companyId = this.$store.getters.companyId;

    
    //获取收入类别
    this.getTypeList();
    //获取项目信息
    this.getProject();
    this.Selectinsertlsit();
  },
  methods: {
    //时间处理
    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;
    },
    timestampToTime() {
      var date = this.incomeFrom.incomeTime;
      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.incomeFrom.incomeTime = Y + M + D + h + m + s;
    },
    //提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          insert(this.incomeFrom)
            .then(res => {
              if (res.success) {
                //判断是否有合同文件
                if (this.fileTypepdf) {
                  this.proutlist1.Id = res.data;
                  this.$refs.upload1.submit();
                }
                //判断是否有选择发票
                if(this.invoiceListAdd.length > 0){
                  let list = [];
                  //提交发票与收入关系 status默认为1 表示发票已报销
                  this.invoiceListAdd.forEach(item => {
                    list.push({
                      invoiceId: item,
                      incomeId: 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.incomeFrom.projectName = this.projectData.projectName;
      this.incomeFrom.projectId = this.projectData.projectId;
    },
    //返回
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        path: "/incomeList",
        query: {
          id: this.$route.query.id,
          backid: this.$route.query.backid
        }
      });
    },
    //合同文件校验
    onChangepdf(file) {
      console.log("2")
      const fileNamepdf = file.name;
      let fileType = fileNamepdf.substring(fileNamepdf.lastIndexOf("."));
      if (fileType == ".pdf") {
        this.fileTypepdf = true;
      } else {
        this.$message.warning("合同文件只能是pdf格式文件");
        this.$refs.upload1.clearFiles();
        this.fileTypepdf = false;
      }
    },
    //获取收入类型
    getTypeList() {
      let param = {
        companyId: this.$store.getters.companyId,
        typeCategory: 0
      };
      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.incomeFrom.projectName = res.data.projectName;
            this.incomeFrom.projectId = res.data.projectId;
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch(error => {
          this.$message.error("获取项目失败");
          this.back();
        });
    },
    //添加发票
    drawerAdd() {
      this.drawer = true;
      this.getincomeSelectlist();
    },
    //添加发票单
    Reimbursement() {
      this.isgetid = 1;
      this.$refs.addTO.resetFields();
    },
    //查询发票信息
    getincomeSelectlist(pager = 1) {
      this.invoicegetList.qurey.pageNum = pager;
      queryBypageIncomeAdd(this.invoicegetList.qurey)
        .then(res => {
          if (res.success) {
            this.invoicegetList.list = res.data.list;
            this.invoicegetList.total = res.data.total;
          } else {
            this.$message.errror(res.msg);
          }
        })
        .catch(error => {
          this.$message.error("查询发票数据失败");
        });
    },
    //校验发票文件格式
    onChange(file) {
      console.log("1")
      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.upload2.clearFiles();
      }
    },
    //添加发票提交
    getlistForm(){
      if(this.fileTypeJpg){
        this.$refs.addTO.validate(valid => {
          if (valid) {
            this.addTO.userId = this.$store.getters.urId
            this.addTO.companyId = this.$store.getters.companyId
            insertList(this.addTO)
              .then(res=>{
                if(res.success){
                  //发票记录添加成功
                  //提交发票文件
                  this.proutlist2.Id = res.data;
                  this.$refs.upload2.submit();
                  this.$message.success(res.msg);
                  this.isgetid = 0;
                  this.addTO = {
                    category: 0, //0收入 1支出 2报销
                    code: null,
                    companyId: null,
                    mone: null,
                    number: null,
                    status: 0,//状态 0未报销 1已报销
                    time: null,
                    type: 0,//0 普票 1专票
                    userId: null
                  }
                  this.$refs.upload2.clearFiles();
                  this.getincomeSelectlist();
                  this.Selectinsertlsit();
                }else{

                  this.$message.errror(res.msg)
                }
              })
              .catch(errpr=>{
                this.$message.errror("发票添加失败")
              })
          }
        }) 
      }else{
        this.$message.warning("没有发票文件，无法提交")
      }
        
    },
    //查询发票编号
    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();
        });
    },
    //清楚合同文件
    delfile1(file, fileList){
      this.fileTypepdf = false
    },
    //清除发片文件
    delfile2(file, fileList){
      this.fileTypeJpg = false
    }
  }
};
</script>

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