<template>
  <div class="container">
    <el-row>
      <el-col :xl="8" :lg="8" :md="8" :sm="12" :xs="24" style="margin:20px 30px;">
        <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="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="danger" icon="el-icon-delete-solid" @click="deleteExpend()">删除</el-button>
            <el-button @click="back()">返回</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :xl="8" :lg="10" :md="12" :sm="12" :xs="24" style="margin:10px 130px;">
        <div>
          <h3>发票编辑</h3>
          <div>
            <div class="selectList" style="margin:20px 0px">
              <el-select
                v-model="getListincom"
                multiple
                filterable
                default-first-option
                style="width:220px;"
                placeholder="请选择要添加的发票编号"
                @change="getchange()"
              >
                <el-option
                  v-for="item in invoiceListAdd"
                  :key="item.invoiceId"
                  :label="item.number"
                  :value="item.invoiceId"
                ></el-option>
              </el-select>
              <el-button type="primary" @click="Buttonback2()" style="margin:0px 5px">添加发票</el-button>
            </div>
          </div>
          <div>
            <el-table
              :data="getinvoivelist"
              border
              style="width: 100%"
              :cell-style="{'text-align':'center'}"
              :header-cell-style="{'text-align':'center', background:'#eef1f6',color:'#606266'}"
              class="gettable"
            >
              <el-table-column prop="code" label="发票代码"></el-table-column>
              <el-table-column prop="number" label="发票号码"></el-table-column>
              <el-table-column prop="mone" label="金额"></el-table-column>
              <el-table-column prop="prop" label="操作">
                <template slot-scope="scope">
                  <el-popover placement="top" width="60" v-model="scope.row.visible">
                    <p>确定要删除该发票吗</p>
                    <div style="text-align: right; margin:0">
                      <el-button size="mini" type="text" @click="scope.row.visible = false">取消</el-button>
                      <el-button type="primary" size="mini" @click="DeleteFrom(scope.row)">确定</el-button>
                    </div>
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      slot="reference"
                      class="edit"
                    >删除</el-button>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { selectAll } from "@/api/type";
import { update, selectById, del } from "@/api/expend";
import { money } from "@/utils/myValidate";
import { mapGetters } from "vuex";
import {
  selectAllById,
  selectAllBystatus,
  updatesubmit,
  deletBystatus
} from "@/api/project";
export default {
  data() {
    return {
      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: [
          {
            validator: money,
            trigger: "change"
          }
        ],
        expendTime: [
          { required: true, message: "请选择支出时间", trigger: "change" }
        ]
      },
      getListincom: [], //收集选择的数组
      invoiceListAdd: [], //查询发票的集合
      getinvoivelist: [],
      backlistid: null //返回标记
    };
  },
  computed: {
    ...mapGetters(["companyId", "urId"]),
    expendId() {
      return this.$route.query.id;
    }
  },
  created() {
    this.backlistid = this.$route.query.backlistid;
    this.expendFrom.userId = this.$store.getters.urId;
    this.getTypeList();
    this.getexpend();
    this.selectGet();
    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();
        });
    },
    //获取支出信息
    getexpend() {
      selectById({ expendId: this.expendId })
        .then(res => {
          if (res.success) {
            this.expendFrom = res.data;
            this.expendFrom.userId = this.$store.getters.urId;
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch(error => {
          this.$message.error("获取信息失败");
          this.back();
        });
    },
    //提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          update(this.expendFrom)
            .then(res => {
              if (res.success) {
                this.$message.success(res.msg);
                this.back();
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch(error => {
              this.$message.error("新建失败");
            });
        }
      });
    },
    //返回
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        path: "/expendList",
        query: {
          id: this.$route.query.projectId,
          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;
    },
    //删除
    deleteExpend() {
      this.$confirm("确定要删除此收入记录吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          del(this.expendFrom)
            .then(res => {
              if (res.success) {
                this.$message.success("删除成功");
                this.back();
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch(error => {
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //添加发票
    Buttonback2() {
      if (this.getListincom.length > 0) {
        let list = [];
        //提交发票与收入关系 status默认为1 表示发票已报销
        this.getListincom.forEach(item => {
          list.push({
            invoiceId: item,
            expendId: this.expendId,
            status: 1
          });
        });
        updatesubmit(list).then(res => {
          if (res.success) {
            this.$message.success(res.msg);
            this.dialogFormVisible = false;
            this.$message({
              showClose: true,
              message: "添加发票成功",
              type: "success"
            });
            this.Selectinsertlsit();
            this.getListincom = [];
          } else {
            this.$message.error(res.msg);
          }
        });
      } else {
        this.$message({
          showClose: true,
          message: "没有添加发票",
          type: "warning"
        });
      }
    },
    //查询未报销发票
    selectGet() {
      const params = {
        userId: this.urId,
        companyId: this.companyId,
        type: 1
      };
      selectAllBystatus(params)
        .then(res => {
          if (res.success) {
            this.invoiceListAdd = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(error => {
          this.$message.error("获取发票编号失败");
        });
    },
    //查询发票图片
    Selectinsertlsit() {
      const params = {
        companyId: this.companyId,
        expendId: this.expendId
      };
      selectAllById(params)
        .then(res => {
          if (res.success) {
            this.getinvoivelist = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(error => {
          console.log(error);
          this.$message.error("获取发票图片失败");
        });
    },
    //删除发票
    DeleteFrom(row) {
      let get = this.expendFrom.expendMoney;
      get -= row.mone;
      console.log(get);
      this.expendFrom.expendMoney = get;
      //收集被删除发票的数据
      let BillList = {
        invoiceId: row.invoiceId,
        expendId: row.expendId
      };
      deletBystatus(BillList)
        .then(res => {
          if (res.success) {
            this.visible = false;
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.Selectinsertlsit();
            this.selectGet();
          }
        })
        .catch(errror => {
          this.$message.error(res.msg);
        });
    },
    //添加发票金额
    getchange() {
      let sum = 0;
      let list = [];
      this.getListincom.forEach(g => {
        this.invoiceListAdd.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;
}
.edit {
  font-size: 11px;
}
</style>