<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
    >
      <el-form-item label="申请编号" >
        <el-input
          v-model="queryParams.appNo"
          placeholder="申请编号"
          clearable
        />
      </el-form-item>
      <el-form-item label="流程状态">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option label="全部" value="">全部</el-option>
          <el-option label="未提交" value="0">未提交</el-option>
          <el-option label="已申请" value="1">已申请</el-option>
          <el-option label="已审核" value="2">已审核</el-option>
          <el-option label="已开票" value="3">已开票</el-option>
          <el-option label="已完成" value="4">已完成</el-option>
          <el-option label="未完成" value="5">未完成</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="当前节点">
        <el-select v-model="queryParams.currentNode" placeholder="请选择">
          <el-option label="全部" value="">全部</el-option>
          <el-option label="开票申请" value="0">开票申请</el-option>
          <el-option label="业务审核" value="2">业务审核</el-option>
          <el-option label="财务审批" value="4">财务审批</el-option>
          <el-option label="财务开票" value="6">财务开票</el-option>
          <el-option label="发票上传" value="8">发票上传</el-option>
          <el-option label="发票接收" value="10">发票接收</el-option>
          <el-option label="财务入账及凭证生成" value="12">财务入账及凭证生成</el-option>
          <el-option label="已完成" value="14">已完成</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单位">
        <el-select
          v-model="selectVal"
          placeholder="请选择..."
          @clear="delValue"
          clearable
          ref="select"
          style="width: 300px"
        >
          <el-option hidden key="id" :value="selectVal" :label="selectName"></el-option>
          <el-tree
            :data="options"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
            :check-on-click-node="true"
            ref="tree"
            node-key="id"
            :default-expand-all="true"
            :filter-node-method="filterNode"
          >
            <span slot-scope="{ data }">
            <span>{{ data.deptName }}</span>
          <el-tag
            size="mini"
            style="margin: 0 10px"
            v-show="filterorgType(data.tag)"
          >{{ filterorgType(data.tag) }}</el-tag
          >
        </span>
          </el-tree>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh"  @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
    </el-row>
    <el-button  type="primary" size="small"  @click="addMal">开票申请</el-button>
    <el-button  type="primary" size="small"  @click="addMalAmend" :disabled="!row || row.status!=0">修改</el-button>
<!--    <el-button  type="primary" size="small"  @click="addAditCom" :disabled="!multipleSelection && (!row || row.status!=0 || (row.haveCommitPermission==0 && moment().format('DD')>=20))">提交审核</el-button>-->
    <el-button  type="primary" size="small"  @click="addAditCom" :disabled="!multipleSelection">提交审核</el-button>
    <el-button  type="danger" size="small"  @click="dangerOut" :disabled="!row || (row.status<=0 || row.status==4)">撤回</el-button>
    <el-button  type="danger" size="small"  @click="deleteData" :disabled="!multipleSelection">删除</el-button>
    <el-button  class="el-icon-document" type="primary" size="small" :disabled="!row"  @click="download" >导出</el-button>
    <el-button  class="el-icon-document" type="primary" size="small"   @click="download1" >导出全部</el-button>
    <div class="table">
      <el-table
        v-loading="loading"
        :data="deptList"
        ref="table"
        row-key="deptId"
        highlight-current-row
        max-height="350px"
        @row-click="rowClick"
        @selection-change="handleSelectionChange"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          type="selection"
          :selectable="selectableStatus"
          width="55">
        </el-table-column>
        <el-table-column
          prop="seriervs"
          label="序号"
          min-width="30"
        ></el-table-column>
        <el-table-column
          prop="appNo"
          label="申请编号"
        >
          <template slot-scope="{row}">
          <span @click="appNoDidet(row)" style="color: #00afff;cursor: pointer">{{row.appNo}}</span>
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          label="开票数量"-->
<!--          align="center"-->
<!--          prop="invoiceNum"-->
<!--        >-->
<!--        </el-table-column>-->
        <el-table-column
          prop="createUserOrgName"
          label="单位"
          min-width="100"
        ></el-table-column>
        <el-table-column prop="status" label="流程状态" >
          <template slot-scope="{row}">
              {{row.status | auditFilter}}
          </template>
        </el-table-column>
        <el-table-column
          label="当前节点"
          align="center"
          prop="nodeLabel"
        >
        </el-table-column>
        <el-table-column
          label="当前审核人"
          align="center"
          prop="currentAuditUserName"
        >
        </el-table-column>
        <el-table-column
          label="创建用户"
          align="center"
          prop="createUserName"
        >
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" >
        </el-table-column>
        <el-table-column prop="commitAuditTime" label="提交审核时间" >
        </el-table-column>
      </el-table>
      <el-pagination
        style="display: flex;justify-content: flex-end ;margin: 15px 0px 0px 0px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" />
      <modal ref="modalDait"/>
      <addmodeal ref="addmodeal" @handele="handele"></addmodeal>
      <comeReview @headel="getList" ref="comeReview"/>
      <modification ref="modification"  @handele="handele"/>
    </div>
  </div>
</template>

<script>
import {
  applyPage, listDept,
} from "@/api/system/dept";
import {
  applyDelete,
  applyInvoiceExport,
  applyInvoiceExportDetail,
  commitAudit,
  downloadTemplate,
  withdraw
} from '@/api/utils'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import  moment from 'moment'
import {dataList} from '@/utils/utiles'
import addmodeal from "@/views/applicationManagement/BillingApplication/components/addmodeal";
import comeReview from "@/views/applicationManagement/BillingApplication/components/comeReview";
import modification from "@/views/applicationManagement/BillingApplication/components/modification";
import modal from "./components/modal";

export default {
  components:{
    addmodeal,comeReview,modal,modification,
  },
  filters: {
    auditFilter(value) {
      const item = dataList.find((res) => res.value == value);
      return item ? item.label : null;
    },
  },
  data() {
    return {
      selectVal:'',
      selectName:'',
      defaultProps: {
        children: "children",
        label: "name",
      },
      // 标签数组
      tagList: [

      ],
      deptList:[],
      value1:null,
      // 遮罩层
      loading: false,
      row:null,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        status: undefined,
        appNo: undefined,
        currentNode:null,
        createUserOrgName:''
      },
      pageNo:1,
      pageSize:10,
      total:0,
      multipleSelection:null,
      options:[],
    };
  },
  created() {
    this.getList();
    this.getListM()
  },
  watch: {
    // 搜索过滤，监听input搜索框绑定的treeFilter
    treeFilter(val) {
      this.$refs.tree.filter(val);
      // 当搜索框键入值改变时，将该值作为入参执行树形控件的过滤事件filterNode
    },
  },
  computed:{
    //审核
    getStatus(val){
       let data=this.dataList.find(f=>f.value==val)
       return data.label
    }
  },
  methods: {
    delValue() {
      this.selectVal = ''
      this.selectName = '';
    },
    // 结构树点击事件
    handleNodeClick(data) {
      console.log(data,'----')
      this.selectVal = data.deptId; // select绑定值为点击的选项的value
      this.selectName = data.deptName; // input中显示值为label
      this.treeFilter = ""; // 点击后搜索框清空
      this.$refs.select.blur(); // 点击后关闭下拉框，因为点击树形控件后select不会自动折叠
    },
    // 模糊查询（搜索过滤），实质为筛选出树形控件中符合输入条件的选项，过滤掉其他选项
    filterNode(value, data) {
      if (!value) return true;
      let filterRes = data.label.indexOf(value) !== -1;
      return filterRes;
    },
    // 选项卡标签（可忽略，增值迭代需求）
    filterorgType(val) {
      let arr = this.tagList.filter((item) => {
        return item.value == val;
      });
      return arr.length ? arr[0].label : "";
    },
    /** 查询部门列表 */
    getListM() {
      listDept().then((response) => {
        this.options = this.handleTree(response.data, "deptId");
      });
    },
    handleSelectionChange(val) {
      if(val.length>0){
        this.multipleSelection = val;
      }else {
        this.multipleSelection = null;
      }
    },
    selectableStatus(row, rowIndex) {
      // 返回false禁用多选
      if(row.status===0){
        return true
      }else {
        return false
      }
      // return !row.disabled;
    },
    //下载
    async download(){
      let res=await applyInvoiceExport({applyId:this.row.id})
      if(res){
        const elink = document.createElement('a');
        elink.download = `${moment().format('YYYY/MM/DD')}.xls`;
        elink.style.display = 'none';
        const blob = new Blob([res], { type: 'application/x-msdownload' });
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      }else {
        this.$message.error('导出异常请联系管理员');
      }
    },
    //下载
    async download1(){
      let res=await applyInvoiceExportDetail()
      if(res){
        const elink = document.createElement('a');
        elink.download = `${moment().format('YYYY/MM/DD')}.xls`;
        elink.style.display = 'none';
        const blob = new Blob([res], { type: 'application/x-msdownload' });
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      }else {
        this.$message.error('导出异常请联系管理员');
      }
    },
    //修改
    addMalAmend(){
      this.$refs.modification.show(this.row)
    },
    dangerOut(){
      let that=this
      this.$confirm('是否撤回?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //点击确定的操作(调用接口)
        let res=await withdraw({id:this.row.id})
        if(res.code==200){
          this.$message.success('撤回成功')
          this.getList()
        }else {
          this.$message.error('撤回失败')
        }
      }).catch(() => {
        //几点取消的提示
      });
    },
    deleteData() {
      console.log(this.multipleSelection)
      this.$confirm('是否删除所选的'+this.multipleSelection.length+'条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //点击确定的操作(调用接口)
        let param = {
          ids:[]
        }
        if(this.multipleSelection.length>0){
          this.multipleSelection.forEach(item=>{
            param.ids.push(item.id)
          })
        }
        let res = await  applyDelete(param)
        if (res.code==200){
          this.$message.success('删除成功')
          this.getList()
        }else {
          this.$message.error(res.msg ? res.msg:'删除失败')
        }
      }).catch(() => {

      });
    },
    moment,
    appNoDidet(row){
       this.$refs.modalDait.handlelist(row)
    },
    addAditCom(){
      console.log(this.$refs)
      this.$refs.comeReview.handle(this.multipleSelection)
    },
    //表格点击
    rowClick(val){
      this.row=val
    },
    handele(){
      this.getList()
    },
    addMal(){
       this.$refs.addmodeal.show()
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      let data={
        pageNo:this.pageNo,
        pageSize:this.pageSize,
      }
      this.queryParams.createUserOrgNo=this.selectVal
      applyPage(this.queryParams,data).then((response) => {
        if(response && response.data && response.data.records){
          this.loading = false;
          this.deptList = response.data.records;
          this.total=response.data.total
          this.deptList.forEach((item,index)=>{
            item.seriervs=index+1
          })
        }else {
          this.loading = false;
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize=val
      this.getList()
    },
    handleCurrentChange(val) {
      this.pageNo=val
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
      this.row=null
      this.multipleSelection=null
      this.$refs.table.setCurrentRow();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams= {
        taskName: undefined,
        applyUserName: undefined,
        startDate:null,
        endDate:null,
        currentNode:null,
       },
        this.value1=null
    },

  },
};
</script>
<style lang="scss" scoped>
.table {
  height: calc(100% - 80px);
  margin-top: 10px;
}
::v-deep {
  .el-table {
    height: 100%;
    width: 100%;
    .el-table__body-wrapper {
      width: 100% !important;
      height: calc(100% - 50px) !important; // 表格高度减去表头的高度
      overflow-y: scroll;
    }
  }
}
 ::v-deep .table .el-table__body tr.current-row>td{
  //　　background-color: #F5F7FA !important;
}
::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td {
  　　background-color: #F5F7FA;
}
</style>
