<template>
  <div class="container">
    <div class="header">
      <el-form :inline="true" :model="incomeQurey">
        <el-form-item label="收入对象">
          <el-input v-model="incomeQurey.incomeObject" placeholder="收入对象"></el-input>
        </el-form-item>
        <el-form-item label="收入类别">
          <el-select v-model="incomeQurey.incomeType">
            <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="incomeQurey.incomeBody" 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="addincome()"
            v-if="state != 0"
          >新增收入</el-button>
          <el-button @click="back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="conter">
      <el-table
        :data="incomeList"
        style="width: 100%; text-align: center"
        border
        :cell-style="{'text-align':'center'}"
        :header-cell-style="{'text-align':'center'}"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" class="demo-table-expand">
              <el-form-item label="收入详情：">
                <span>{{ props.row.incomeInformation }}</span>
              </el-form-item>
              <el-form-item label="收入备注：">
                <span>{{ props.row.incomeRemarks }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>

        <el-table-column label="序号" width="50px">
          <template slot-scope="scope">
            {{
            (incomeQurey.pageNum - 1) * incomeQurey.pageSize +
            scope.$index +
            1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="projectName" label="项目名称" />
        <el-table-column prop="incomeObject" 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="incomeMoney" label="收入金额" />

        <el-table-column prop="incomeBody" label="收入内容" />

        <el-table-column prop="incomeTime" 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">
          <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="incomeQurey.pageNum"
        :page-size="incomeQurey.pageSize"
        layout="total, prev, pager, next"
        :total="total"
      ></el-pagination>
    </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
          :cell-style="{'text-align':'center'}"
          :header-cell-style="{'text-align':'center'}"
        >
          <el-table-column type="index" label="序号" width="80px"></el-table-column>
          <el-table-column prop="number" label="号码" width="160px"></el-table-column>
          <el-table-column prop="mone" label="金额" width="180px"></el-table-column>
          <el-table-column prop="prop" label="查看PDF文件或图片" width="180px">
            <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
             
              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>
      <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="index.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>
</template>

<script>
import { selectByProjectId } from "@/api/imcome";
import { selectAll } from "@/api/type";
import {
  selectAllById,
  selectByIdF,
  selectAllBystatus,
  updatesubmit,
  deletBystatus,
  deleteById
} from "@/api/project";
import { componentMap } from "../../../router";

const InitialData = {
  incomeBody: null,
  incomeInformation: null,
  incomeMoney: null,
  incomeObject: null,
  incomeRemarks: null,
  incomeTime: null,
  incomeType: null,
  projectId: null,
  userId: null,
  projectName: null
};

export default {
  data() {
    return {
      visible: false,
      incomeQurey: {
        projectId: null,
        pageNum: 1,
        pageSize: 10,
        incomeObject: null,
        incomeType: null,
        incomeBody: null,
        incomeTimeStart: null,
        incomeTimeEnd: null
      },
      incomeList: [],
      options: [],
      mainTime: null,
      total: 0,
      dialogVisible: false,
      incomeFrom: {},
      //抽屉
      drawer: false,
      direction: "rtl",
      //查询图片给的值
      getinvoiveId: {
        companyId: null,
        incomeId: 0
      },
      //图片的数组
      getinvoivelist: [],
      //图片数组
      srcList: [],
      backid: null,
      //查询附件
      queryDTO: {
        companyId: null,
        incomeId: null
      },
      queryDTOList: [], //收集附件的数据
      //附件抽屉
      drawer2: false,
      //发票对话框
      dialogFormVisible: false,
      invoiceListAdd: [], //查询发票的集合
      getFormslist: {
        userId: null,
        companyId: null,
        type: 0
      }, //查询的能选择的表单信息
      getListincom: [], //收集选择的数组
      incomeIdgrt: null, //收集incomeId数据
      getshow: 1, //判断show的显示与隐藏,
      //合同文件上传携带参数
      proutlist1: {
        Id: null,
        enclosureDescribe: "",
        status: 0, //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.incomeQurey.projectId = this.$route.query.id;
    this.backid = this.$route.query.backid;
    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.getIncome();
    this.getTypeList();
  },
  methods: {
    //获取收入类型
    getTypeList() {
      let param = {
        companyId: this.$store.getters.companyId,
        typeCategory: 0
      };
      selectAll(param)
        .then(res => {
          if (res.success) {
            this.options = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(error => {
          this.$message.error("获取类型失败");
        });
    },
    //获取收入情况
    getIncome() {
      selectByProjectId(this.incomeQurey)
        .then(res => {
          if (res.success) {
            this.incomeList = res.data.list;
            this.total = res.data.total;
          } else {
            this.$message.errror(res.msg);
          }
        })
        .catch(error => {
          this.$message.error("查询数据失败");
        });
    },
    //换页
    handleCurrentChange(val) {
      this.incomeQurey.pageNum = val;
      this.getIncome();
    },
    //时间处理
    time(val) {
      if (val == null) {
        this.incomeQurey.incomeTimeStart = null;
        this.incomeQurey.incomeTimeEnd = null;
      } else {
        this.incomeQurey.incomeTimeStart = this.timestampToTime(val[0]);
        this.incomeQurey.incomeTimeEnd = 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;
    },
    //查询
    qurey() {
      this.incomeQurey.pageNum = 1;
      this.getIncome();
    },
    //重置
    reset() {
      this.incomeQurey.incomeTimeStart = null;
      this.incomeQurey.incomeTimeEnd = null;
      this.mainTime = null;
      this.incomeQurey.incomeObject = null;
      this.incomeQurey.incomeType = null;
      this.incomeQurey.incomeBody = null;
      this.qurey();
    },
    //时间处理 yyyy-MM-dd hh:mm:ss
    timestampToTime2() {
      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;
    },
    //添加按钮事件
    addincome() {
      this.$router.push({
        path: "/incomeAdd",
        query: {
          id: this.$route.query.id,
          backid: this.backid
        }
      });
    },
    //查看项目附件.....
    selectImage(row) {
      this.queryDTO.incomeId = row.incomeId;
      this.proutlist1.Id = row.incomeId;
      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("获取附件文件失败");
        });
    },
    //查看pdf的方法
    ReviseImage(row) {
      this.drawer = true;
      this.getinvoiveId.incomeId = row.incomeId;
      this.incomeIdgrt = row.incomeId;
      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 == ".jpg") {
                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();
        });
    },
    //修改方法
    updatain(data) {
      this.$router.push({
        path: "/incomeUpdata",
        query: {
          id: data.incomeId,
          projectId: this.$route.query.id
        }
      });
    },
    //返回开始
    back() {
      if (this.backid == 0) {
        this.$router.push({
          path: "/projectList",
          query: {
            id: this.$route.query.id
          }
        });
      } else if (this.backid == 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;
      console.log(photopath);
      window.open(photopath, "_blank");
    },

    //下载附件
    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.target = "_blank";
      a.style.display = "none"; // 障眼法藏起来a标签
      document.body.appendChild(a); // 将a标签追加到文档对象中
      a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      a.remove(); // 一次性的，用完就删除a标签
    },
    //查询未报销发票
    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.selectGet();
      this.dialogFormVisible = false;
      this.getListincom = [];
    },
    Buttonback2() {
      let list = [];
      //提交发票与收入关系 status默认为1 表示发票已报销
      this.getListincom.forEach(item => {
        list.push({
          invoiceId: item,
          incomeId: 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,
        incomeId: row.incomeId
      };
      deletBystatus(BillList)
        .then(res => {
          if (res.success) {
            this.visible = false;
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.Selectinsertlsit();
          }
        })
        .catch(errror => {
          this.$message.error(res.msg);
        });
    },

    // 附件-------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(file) {
      this.fileList1 = this.fileList1.filter(item => item.uid !== file.uid);
      this.proutlist1.enclosureDescribe = ""; //初始化数据
      this.fileTypepdf = false;
    },
    //确定提交附件
    determine() {
      //判断是否有附件文件
      if (this.fileTypepdf) {
        this.proutlist1.userId = this.$store.getters.urId;
        this.proutlist1.companyId = this.$store.getters.companyId;
        this.$refs.upload1.submit();
        this.getshow = 1; //隐藏与显示
        this.disabled = false;
        //this.backii();
        this.$message({
          showClose: true,
          message: "上传附件成功",
          type: "success"
        });
        this.Refresh();
      } else {
        this.$message.error("请添加附件，在进行提交");
      }
    },
    //刷新附件
    Refresh() {
      this.queryDTO.incomeId = 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("获取附件文件失败");
        });
    },
    //附件取消
    remove() {
      if (this.queryDTOList.length > 0) {
        this.getshow = 1;
        this.disabled = false;
        this.delfile1();
      } else {
        this.getshow = 3;
        this.disabled = false;
        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;
      }
    },
    //图片格式
    formatProtocolType(row) {
      //这里判断的是是否有文件
      if (row.filePath == null) {
        return flase;
      } 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;
    },
  }
};
</script>

<style scoped>
.container {
  padding: 10px;
}
.conter {
  margin-bottom: 10px;
}
.footer {
  text-align: right;
}
.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>