<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
              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-button type="primary" @click="dialogFormVisible = true"
          >上传附件</el-button
        >
        <el-dialog title="附件" :visible.sync="dialogFormVisible" width="55%">
          <div style="width: 60%; margin-left: 30px">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入附件详情"
              v-model="proutlist1.enclosureDescribe"
              style="margin: 20px 0px"
            ></el-input>
            <el-upload
              class="upload-demo"
              ref="upload1"
              drag
              :action="action1"
              :file-list="fileList1"
              :on-remove="delfile1"
              :auto-upload="false"
              :on-change="onChangepdf"
              :data="proutlist1"
              multiple
              style="margin: 20px 0px"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传附件</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传文件，且不超过500kb
              </div>
            </el-upload>
          </div>
          <div style="margin-left: 75%">
            <el-button @click="remove()">取 消</el-button>
            <el-button
              type="primary"
              @click="dialogFormVisible = false"
              style="margin-top: 20px"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </el-col>
      <!-- 按钮 -->
      <el-col :span="24" style="margin-left: 120px">
        <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 @click="back()">返回</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  selectByProjectId,
  selectAllBystatus,
  updatesubmit,
} from "@/api/project";
import { selectAll } from "@/api/type";
import { insert } from "@/api/imcome";
import { money } from "@/utils/myValidate";
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" },
        ],
        incomeObject: [
          { required: true, message: "没有输入对方户名", trigger: "change" },
        ],
        incomeBody: [
          { required: true, message: "没有输入对收入内容", trigger: "change" },
        ],
        incomeMoney: [
          {
            required: true,
            validator: money,
            trigger: "change",
          },
        ],
        incomeTime: [
          { required: true, message: "请选择收到时间", trigger: "change" },
        ],
      },
      invoiceListAdd: [], //选择的发票号
      getinvoivelist: [], //查询的能选择的表单信息
      typeList: [], //收入类型列表
      fileTypepdf: false, //判断合同文件是否存在
      fileList1: [], //合同文件
      //合同文件上传携带参数
      proutlist1: {
        Id: null,
        enclosureDescribe: "",
        status: 0, //0收入 1支出
        companyId: null,
        userId: null,
      },
      //查询发票编号的参数
      getinvoiveId: {
        userId: null,
        companyId: null,
        type: 0,
      },
      //附件
      dialogFormVisible: false,
    };
  },
  computed: {
    projectId() {
      return this.$route.query.id;
    },
  },
  created() {
    //用户id
    this.incomeFrom.userId = this.$store.getters.urId;
    //合同上传地址
    this.action1 = process.env.VUE_APP_BASE_API + "/file/updataEnclosures";
    this.getinvoiveId.userId = this.$store.getters.urId;
    this.getinvoiveId.companyId = this.$store.getters.companyId;
    this.proutlist1.userId = this.$store.getters.urId;
    this.proutlist1.companyId = this.$store.getters.companyId;

    //获取收入类别
    this.getTypeList();
    //获取项目信息
    this.getProject();
    this.Selectinsertlsit();
  },
  methods: {
    //时间处理
    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(this.proutlist1);
      const fileNamepdf = file.name;
      let fileType = fileNamepdf.substring(fileNamepdf.lastIndexOf("."));
      if (fileType != "") {
        this.fileTypepdf = true;
      } else {
        this.$message.warning("附件只能只能上传文件");
        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();
        });
    },
    //查询发票编号
    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() {
      this.fileTypepdf = false;
      this.fileList1 = this.fileList1.filter((item) => item.uid !== file.uid);
    },
    //取消
    remove() {
      this.proutlist1.enclosureDescribe = null;
      this.delfile1();
      this.dialogFormVisible = false;
    },
  },
};
</script>

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