<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="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
              @change="getchange()"
              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="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>
      </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="action2"
              :file-list="fileList1"
              :on-remove="delfile1"
              :auto-upload="false"
              :on-change="onChangepdf"
              :data="proutlist1"
              :on-success="fileSuccess"
              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">
                只能上传jpd文件，且不超过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-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 @click="back()">返回</el-button>
        <!-- </el-form-item> -->
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  selectByProjectId,
  selectAllBystatus,
  updatesubmit,
} from "@/api/project";
import { selectAll } from "@/api/type";
import { insert } from "@/api/expend";
import { expendAdd as rules } from "../rules";
export default {
  data() {
    return {
      rules: rules,
      action2: null,
      fileList1: [],
      expendFrom: {
        expendBody: null,
        expendInformation: null,
        expendMoney: null,
        expendObject: null,
        expendRemarks: null,
        expendTime: null,
        expendType: null,
        projectId: null,
        userId: null,
        projectName: null,
      },
      typeList: [],
      projectData: {},
      companyId: 0,
      typeList: [],
      projectData: {},
      //发票状态
      status: 0,
      //发票编号数组
      getinvoivelist: [],
      //收集发票编号
      invoiceListAdd: [],
      //查询发票编号的数组
      getinvoiveId: {
        userId: null,
        companyId: null,
        type: 1,
      },
      pageNum: 10,
      total: 1,
      //收集数据
      newList: [],
      //保存图片
      proutlist: {
        Id: null,
        status: 1,
      },
      //保存支出附件
      proutlist1: {
        Id: null,
        enclosureDescribe: "",
        status: 1, //0收入 1支出
        companyId: null,
        userId: null,
        "X-Token": null,
      },
      fileType: null,
      fileTypepdf: false,
      backlistid: null,
      fileTypeJpg: null,
      //附件
      dialogFormVisible: false,
    };
  },
  computed: {
    projectId() {
      return this.$route.query.id;
    },
  },
  created() {
    this.expendFrom.userId = this.$store.getters.urId;
    this.getinvoiveId.companyId = this.$store.getters.companyId;
    this.getinvoiveId.userId = this.$store.getters.urId;
    this.action2 = process.env.VUE_APP_BASE_API + "/file/updataEnclosures";
    this.proutlist1["X-Token"] = this.$store.getters.token;
    this.proutlist1.userId = this.$store.getters.urId;
    this.proutlist1.companyId = this.$store.getters.companyId;
    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);
                if (this.fileTypepdf) {
                  //进行支出附件的上传
                  //上传支出附件
                  this.proutlist1.Id = res.data;
                  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;
    },
    //支出附件图片
    onChangepdf(file) {
      const fileNamepdf = file.name;
      let fileType = fileNamepdf.substring(fileNamepdf.lastIndexOf("."));
      if (fileType != "") {
        this.fileTypepdf = true;
      } else {
        this.$message.warning("附件文件只能上传文件");
        this.$resf.upload1.clearFiles();
        this.fileTypepdf = false;
      }
      console.log(this.fileTypepdf);
    },
    //清楚支出附件文件
    delfile1(file) {
      this.fileTypepdf = false;
      this.fileList1 = this.fileList1.filter((item) => item.uid !== file.uid);
    },
    //文件上传成功
    fileSuccess(res) {
      if (res.success) {
        this.$message.success(res.msg);
      } else {
        this.$message.error(res.msg);
      }
    },
    //////发票区域//////
    //查询发票编号
    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();
        });
    },
    //取消
    remove() {
      this.proutlist1.enclosureDescribe = null;
      this.fileList1 = this.fileList1.filter((item) => item.uid !== file.uid);
      this.dialogFormVisible = false;
    },
    //添加发票金额
    getchange() {
      let sum = 0;
      let list = [];
      this.invoiceListAdd.forEach((g) => {
        this.getinvoivelist.forEach((item) => {
          if (item.invoiceId == g) {
            list.push({
              mone: item.mone,
            });
          }
        });
      });
      list.forEach((item) => {
        sum += item.mone;
      });
      this.expendFrom.expendMoney = sum;
    },
  },
};
</script>

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