<template>
  <div class="container">
    <div class="header">
      <el-form :inline="true" :model="expendQurey">
        <el-form-item label="收入对象">
          <el-input v-model="expendQurey.expendObject" placeholder="收入对象"></el-input>
        </el-form-item>
        <el-form-item label="收入类别">
          <el-select v-model="expendQurey.expendType">
            <el-option
              v-for="item in options"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="收入内容">
          <el-input v-model="expendQurey.expendBody" placeholder="收入内容"></el-input>
        </el-form-item>

        <el-form-item label="收入时间">
          <el-date-picker
            v-model="mainTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="time"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="qurey()">查询</el-button>
          <el-button type="primary" icon="el-icon-refresh-right" @click="reset()">重置</el-button>
          <el-button
            type="success"
            icon="el-icon-circle-plus-outline"
            @click="addexpend()"
            v-if="state != 0"
          >新增支出</el-button>
          <el-button @click="back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="conter">
      <el-table
        :data="expendList"
        style="width: 100%; text-align: center"
        border
        :cell-style="{'text-align':'center'}"
        :header-cell-style="{'text-align':'center'}"
      >
        <el-table-column label="序号" width="50px">
          <template slot-scope="scope">
            {{
            (expendQurey.pageNum - 1) * expendQurey.pageSize +
            scope.$index +
            1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="projectName" label="项目名称" />
        <el-table-column prop="expendObject" label="支出对象" />
        <el-table-column prop="expendMoney" label="支出金额" />

        <el-table-column prop="typeName" label="支出类别">
          <template slot-scope="scope">
            <el-tag effect="dark">{{ scope.row.typeName }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="expendBody" label="支出内容" />

        <el-table-column prop="expendTime" label="支出时间" />
        <el-table-column prop="expendInformation" label="支出详情" />
        <el-table-column prop="expendRemarks" label="支出备注" />
        <el-table-column prop="prop" label="发票文件">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="ReviseImage(scope.row)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="附件下载">
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click="selectImage(scope.row)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作人员">
          <template slot-scope="scope">
            <el-tag effect="plain">{{ scope.row.userName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="projectAmount" label="操作" v-if="state != 0" width="120px">
          <template slot-scope="scope">
            <el-button
              style="margin: 5px"
              size="mini"
              icon="el-icon-edit"
              type="info"
              @click="updatain(scope.row)"
            >修改信息</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="footer">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="expendQurey.pageNum"
        :page-size="expendQurey.pageSize"
        layout="total, prev, pager, next"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 附件抽屉 -->
    <div>
      <el-drawer title="附件操作" :visible.sync="drawer2" :direction="direction" size="50%">
        <el-button
          type="primary"
          style=" margin-left:5%;margin-top:40px "
          :disabled="disabled"
          @click="updatecard"
        >添加附件</el-button>

        <el-card
          class="box-card"
          style="width:90%; margin-left:5%; margin-top:20px"
          v-show="getshow==1"
        >
          <el-row class="row-bg">
            <div v-for="index in queryDTOList" :key="index.enclosureId" class="lsitall">
              <el-col :span="10">
                <div style=" margin-top: 6px;margin-left:40px">附件{{index.enclosureId}}</div>
              </el-col>
              <el-col :span="12" style="margin-left:-50px">
                <el-button
                  type="primary"
                  icon="el-icon-folder-checked"
                  class="a-style"
                  size="mini"
                  style=" font-size: 13px"
                  @click="delProject(index)"
                >下载</el-button>

                <el-popover placement="top" width="160" v-model="index.visible">
                  <p>确定要删除此条附件吗</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="visible = false">取消</el-button>
                    <el-button type="primary" size="mini" @click="deleteProject(index)">确定</el-button>
                  </div>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    class="a-style"
                    size="mini "
                    style="font-size: 13px"
                    slot="reference"
                  >删除</el-button>
                </el-popover>
              </el-col>
            </div>
          </el-row>
        </el-card>
        <!-- 附件上传 -->
        <el-card
          class="box-card"
          style="width:90%; margin-left:5%; margin-top:20px"
          v-show="getshow==0"
        >
          <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"
              :on-success="Refresh"
              :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="determine()" style="margin-top:20px;">确 定</el-button>
          </div>
        </el-card>

        <div class="box-card" v-show="getshow==3"></div>
      </el-drawer>
    </div>
    <div>
      <!--抽屉-->
      <el-drawer title="发票详情" :visible.sync="drawer" :direction="direction" size="60%">
        <!-- filePath-->
        <el-button type="primary" style="margin:10px 3%" @click="selectGet()">添加收入发票</el-button>
        <el-table
          :data="getinvoivelist"
          style="width: 94%; margin:10px 3%; text-align: center"
          border
        >
          <el-table-column type="index" label="序号" width="40"></el-table-column>
          <el-table-column prop="number" label="号码" width="160px"></el-table-column>
          <el-table-column prop="mone" label="金额" width="180"></el-table-column>
          <el-table-column prop="prop" label="查看PDF文件或图片">
            <template slot-scope="scope">
              <div v-if="formatProtocolType(scope.row)">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="getimagin(scope.row)"
                  :preview-src-list="srcList"
                ></el-image>
              </div>
              <div v-else>
                <a class="a-style" @click="handlePreView(scope.row)">点击查看文件</a>
              </div>
            </template>
          </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="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"></el-button>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </div>
    <!-- 添加发票对话框 -->
    <div>
      <el-dialog title="添加发票" :visible.sync="dialogFormVisible" width="40%">
        <div class="dialog-footer">
          <div class="selectList">
            <el-select
              v-model="getListincom"
              multiple
              filterable
              allow-create
              default-first-option
              style="width:100%;"
              placeholder="请选择要添加的发票编号"
            >
              <el-option
                v-for="item in invoiceListAdd"
                :key="item.invoiceId"
                :label="item.number"
                :value="item.invoiceId"
              ></el-option>
            </el-select>
          </div>
          <div slot="footer">
            <el-button @click="Buttonback1()">取 消</el-button>
            <el-button type="primary" @click="Buttonback2()">确 定</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { selectAll } from "@/api/type";
import { selectByProjectId } from "@/api/expend";
import {
  selectAllById,
  selectByIdF,
  selectAllBystatus,
  updatesubmit,
  deletBystatus,
  deleteById
} from "@/api/project";
export default {
  data() {
    return {
      visible: false,
      expendQurey: {
        projectId: null,
        pageNum: 1,
        pageSize: 10,
        expendObject: null,
        expendType: null,
        expendBody: null,
        expendTimeStart: null,
        expendTimeEnd: null
      },
      expendList: [],
      options: [],
      mainTime: null,
      total: 0,
      //抽屉
      drawer: false,
      direction: "rtl",
      //查询图片给的值
      getinvoiveId: {
        companyId: null,
        expendId: 0
      },
      //图片的数组
      getinvoivelist: [],
      //图片数组
      srcList: [],
      //返回的标记
      backlistid: null,
      // //查询附件
      queryDTO: {
        companyId: null,
        expendId: null
      },
      //附件抽屉
      drawer2: false,
      //发票对话框
      dialogFormVisible: false,
      //展示抽屉的数组
      queryDTOList: [],
      //查询的能选择的表单信息
      getFormslist: {
        userId: null,
        companyId: null,
        type: 1
      },
      incomeIdgrt: null, //收集incomeId数据
      invoiceListAdd: [], //查询发票的集合
      getListincom: [], //收集选择的数组
      getshow: 1, //判断show的显示与隐藏,
      //合同文件上传携带参数
      proutlist1: {
        Id: null,
        enclosureDescribe: "",
        status: 1, //0收入 1支出
        companyId: null,
        userId: null
      },
      fileTypepdf: false, //判断合同文件是否存在
      fileList1: [], //合同文件
      disabled: false //隐藏
    };
  },
  computed: {
    state: function() {
      return this.$route.query.state;
    }
  },
  created() {
    this.getinvoiveId.companyId = this.$store.getters.companyId;
    this.expendQurey.projectId = this.$route.query.id;
    this.backlistid = this.$route.query.backlistid;
    this.queryDTO.companyId = this.$store.getters.companyId;
    this.getFormslist.companyId = this.$store.getters.companyId;
    this.action1 = process.env.VUE_APP_BASE_API + "/file/updataEnclosures";
    this.proutlist1.userId = this.$store.getters.urId;
    this.proutlist1.companyId = this.$store.getters.companyId;
    this.getexpend();
    this.getTypeList();
  },
  methods: {
    //获取支出情况
    getexpend() {
      selectByProjectId(this.expendQurey)
        .then(res => {
          if (res.success) {
            this.expendList = res.data.list;
            this.total = res.data.total;
          } else {
            this.$message.errror(res.msg);
          }
        })
        .catch(error => {
          this.$message.error("查询数据失败");
        });
    },
    //获取支出类型
    getTypeList() {
      let param = {
        companyId: this.$store.getters.companyId,
        typeCategory: 1
      };
      selectAll(param)
        .then(res => {
          if (res.success) {
            this.options = res.data;
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch(error => {
          this.$message.error("获取类型失败");
          this.back();
        });
    },
    //换页
    handleCurrentChange(val) {
      this.expendQurey.pageNum = val;
    },
    //新增支出信息
    addexpend() {
      this.$router.push({
        path: "/expendAdd",
        query: {
          id: this.$route.query.id,
          backlistid: this.backlistid
        }
      });
    },
    //修改支出信息
    updatain(data) {
      this.$router.push({
        path: "/expendUpdata",
        query: {
          id: data.expendId,
          projectId: this.$route.query.id
        }
      });
    },
    //时间处理
    time(val) {
      if (val == null) {
        this.expendQurey.expendTimeStart = null;
        this.expendQurey.expendTimeEnd = null;
      } else {
        this.expendQurey.expendTimeStart = this.timestampToTime(val[0]);
        this.expendQurey.expendTimeEnd = this.timestampToTime(val[1]);
      }
    },
    //时间处理
    timestampToTime(date) {
      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();
      return Y + M + D + h + m + s;
    },
    //下载附件
    delProject(row) {
      var a = document.createElement("a"); //创建一个<a></a>标签
      a.href = process.env.VUE_APP_BASE_API + row.enclosureFile; // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
      a.download = row.enclosureFile; //设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
      a.style.display = "none"; // 障眼法藏起来a标签
      document.body.appendChild(a); // 将a标签追加到文档对象中
      a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      a.remove(); // 一次性的，用完就删除a标签
    },
    //查询
    qurey() {
      this.expendQurey.pageNum = 1;
      this.getexpend();
    },
    //重置
    reset() {
      this.expendQurey.expendTimeStart = null;
      this.expendQurey.expendTimeEnd = null;
      this.mainTime = null;
      this.expendQurey.expendObject = null;
      this.expendQurey.expendType = null;
      this.expendQurey.expendBody = null;
      this.qurey();
    },
    //查看图片的方法
    ReviseImage(row) {
      this.drawer = true;
      this.getinvoiveId.expendId = row.expendId;
      this.incomeIdgrt = row.expendId;
      this.Selectinsertlsit();
    },
    //查询发票图片
    Selectinsertlsit() {
      selectAllById(this.getinvoiveId)
        .then(res => {
          if (res.success) {
            this.getinvoivelist = res.data;
            this.srcList = [];
            res.data.forEach(e => {
              let fileNamepdf = e.filePath;
              let fileType = fileNamepdf.substring(
                fileNamepdf.lastIndexOf(".")
              );
              if (fileType != ".pdf") {
                this.srcList.push(process.env.VUE_APP_BASE_API + e.filePath);
              }
            });
          } else {
            this.$message.error(res.msg);
            //this.back();
          }
        })
        .catch(error => {
          this.$message.error("获取发票图片失败");
          //this.back();
        });
    },
    back() {
      if (this.backlistid == 0) {
        this.$router.push({
          path: "/projectList",
          query: {
            id: this.$route.query.id
          }
        });
      } else if (this.backlistid == 1) {
        this.$router.push({
          path: "/beresponsibleforList",
          query: {
            id: this.$route.query.id
          }
        });
      } else {
        this.$router.push({
          path: "/participateinList",
          query: {
            id: this.$route.query.id
          }
        });
      }
    },
    //点击查看发票
    handlePreView(row) {
      const photopath = process.env.VUE_APP_BASE_API + row.filePath;
      window.open(photopath, "_blank");
    },
    //查看项目附件.....
    selectImage(row) {
      this.queryDTO.expendId = row.expendId;
      this.proutlist1.Id = row.expendId;
      selectByIdF(this.queryDTO)
        .then(res => {
          if (res.success) {
            this.queryDTOList = res.data;
            if (this.queryDTOList.length > 0) {
              this.drawer2 = true;
              this.getshow = 1;
              this.disabled = false;
            } else {
              this.drawer2 = true;
              this.disabled = false;
              this.getshow = 3;
            }
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(error => {
          this.$message.error("获取附件文件失败");
        });
    },
    //查询未报销发票
    selectGet() {
      this.dialogFormVisible = true;
      this.getFormslist.userId = this.$store.getters.urId;
      selectAllBystatus(this.getFormslist)
        .then(res => {
          if (res.success) {
            this.invoiceListAdd = res.data;
          } else {
            this.$message.error(res.msg);
            this.back();
          }
        })
        .catch(error => {
          this.$message.error("获取发票编号失败");
          this.back();
        });
    },
    //确定与取消
    Buttonback1() {
      this.getListincom = [];
      this.dialogFormVisible = false;
    },
    Buttonback2() {
      let list = [];
      //提交发票与收入关系 status默认为1 表示发票已报销
      this.getListincom.forEach(item => {
        list.push({
          invoiceId: item,
          expendId: this.incomeIdgrt,
          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);
        }
      });
    },
    //删除发票
    DeleteFrom(row) {
      //收集被删除发票的数据
      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();
          }
        })
        .catch(errror => {
          this.$message.error(res.msg);
        });
    },
    //图片格式
    formatProtocolType(row) {
      //这里判断的是是否有文件
      if (row.filePath == null) {
        return false;
      } else {
        let fileNamepdf = row.filePath;
        let fileType = fileNamepdf.substring(fileNamepdf.lastIndexOf("."));
        if (fileType != ".pdf") {
          return true;
        } else {
          return false;
        }
      }
    },
    getimagin(row) {
      return process.env.VUE_APP_BASE_API + row.filePath;
    },

    // 附件-------0-----------
    //显示添加附件
    updatecard() {
      this.getshow = 0;
      this.disabled = true;
      this.delfile1();
    },
    //删除附件
    deleteProject(row) {
      deleteById(row)
        .then(res => {
          if (res.success) {
            this.selectImage(row);
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.visible = false;
          }
        })
        .catch(errror => {
          this.$message.error(res.msg);
        });
    },
    //清除附件文件
    delfile1() {
      this.fileList1 = this.fileList1.filter(item => item.uid !== file.uid);
      this.fileTypepdf = false;
    },
    //确定提交附件
    determine() {
      //判断是否有附件文件
      if (this.fileTypepdf) {
        this.$refs.upload1.submit();
        this.getshow = 1;
        this.disabled = false;
        this.$message({
          showClose: true,
          message: "上传附件成功",
          type: "success"
        });
        this.Refresh();
      } else {
        this.$message.error("请添加附件，在进行提交");
      }
    },
    //刷新附件
    Refresh() {
      this.queryDTO.expendId = this.proutlist1.Id;
      selectByIdF(this.queryDTO)
        .then(res => {
          if (res.success) {
            this.queryDTOList = res.data;
            this.proutlist1.enclosureDescribe = ""; //初始化数据
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(error => {
          this.$message.error("获取附件文件失败");
        });
    },
    //初始化数据
    backii() {
      this.proutlist1 = {
        Id: null,
        enclosureDescribe: "",
        status: 0, //0收入 1支出
        companyId: null,
        userId: null
      };
    },
    //附件取消
    remove() {
      if (this.queryDTOList.length > 0) {
        this.getshow = 1;
        this.disabled = false;
        this.backii();
        this.delfile1();
      } else {
        this.getshow = 3;
        this.disabled = false;
        this.backii();
        this.delfile1();
      }
    },
    //附件文件校验
    onChangepdf(file) {
      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;
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 10px;
}
.conter {
  margin-bottom: 10px;
}
.footer {
  text-align: right;
}
.conter {
  margin-bottom: 10px;
}
.lsitall .el-col {
  margin: 20px 10px;
}
.lsitall .el-button {
  margin-left: 16px;
}
.row-bg {
  margin-left: 15%;
}
.dialog-footer {
  width: 90%;
  margin: 20px 5%;
}
.selectList {
  margin-bottom: 60px;
}
</style>