<!--采购申请-->
<template>
  <div class="app-container purchaseRequisition">
    <div class="purchaseRequisition-page" v-if="pageType == 1">
      <el-form :model="queryParamsData" class="form-box" ref="queryForm" :inline="true">
        <el-form-item label="关键字" prop="searchValue">
          <el-input
            maxLength="30"
            v-model="queryParamsData.searchValue"
            placeholder="编号/姓名/化学品名/实验室"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态" prop="approvalStatus">
          <el-select v-model="queryParamsData.approvalStatus" clearable placeholder="请选择状态" style="width: 140px">
            <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-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="terminalStatus">
          <el-date-picker
            :clearable="false"
            v-model="dateRangeOne"
            size="small"
            style="width: 220px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间" prop="terminalStatus">
          <el-date-picker
            :clearable="false"
            v-model="dateRangeTwo"
            size="small"
            style="width: 220px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <p class="inquire-button-one" @click="handleQuery" style="margin-right:10px;">查询</p>
          <p class="reset-button-one" @click="resetQuery">重置</p>
        </el-form-item>
        <el-form-item style="float: right;">
          <el-col :span="1.5">
            <p class="inquire-button-one"
               style="width:100px;"
               v-hasPermi="['chemical:hxpapply:add']"
               @click="pageToggle(3)"
            >申购</p>
          </el-col>
        </el-form-item>
        <el-form-item style="float: right;">
          <el-col :span="1.5">
            <p class="add-button-one-90"
               style="width:100px;"
               v-hasPermi="['chemical:hxpapply:draftsList']"
               @click="pageToggle(2)"
            >草稿箱</p>
          </el-col>
        </el-form-item>
        <el-form-item style="float: right;">
          <el-dropdown @command="exportButton" v-hasPermi="['chemical:hxpapply:export']">
            <div class="form-dropdown-box">
              <img src="@/assets/ZDimages/personnelManagement/icon_jzgxx_sc.png">
              <p>导出</p>
              <img src="@/assets/ZDimages/personnelManagement/icon_jzggl_xljt.png">
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item style="border-bottom:1px solid #E0E0E0;margin:0 10px;color:#333;" :command="{command:1}">导出全部数据</el-dropdown-item>
              <el-dropdown-item style="margin:0 10px;color:#666;" :command="{command:2}">导出选中数据</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
      </el-form>
      <el-table  border :data="tableList" ref="multipleTable" @selection-change="handleSelectionChange" :row-key="getRowKeys">
        <el-table-column type="selection" width="50" align="center" :reserve-selection="true"/>
        <el-table-column label="申购编号" align="center" prop="applyNum" width="150"/>
        <el-table-column label="申购人" align="center" prop="subscriber" width="110"/>
        <el-table-column label="实验室" align="center" prop="subName" width="160" show-overflow-tooltip/>
        <el-table-column label="申购信息" align="center" prop="chemicalNames" >
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" placement="top">
              <div v-html="(scope.row.chemicalNames).replace(/;/g, '<br />')" slot="content" v-if="scope.row.chemicalNames"></div>
              <div class="oneLine" style="display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                {{scope.row.chemicalNames}}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="createTime" width="170"/>
        <el-table-column label="完成时间" align="center" prop="overTime" width="170"/>
        <el-table-column label="状态" align="center" prop="approvalContent" width="100"/>
        <el-table-column label="审批人" align="center" prop="status" width="130">
          <template slot-scope="scope">
            <div>
              <el-tooltip class="item" effect="dark" :content="scope.row.dqName?'当前：'+scope.row.dqName:'当前：无'" placement="top">
                <div style="display: flex">
                  <p>当前：</p>
                    <p style="flex:1;text-align: left;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">{{scope.row.dqName?scope.row.dqName:'无'}}</p>
                </div>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" :content="scope.row.lsName?'历史：'+scope.row.lsName:'历史：无'" placement="top">
                <div style="display: flex">
                  <p>历史：</p>
                  <p style="flex:1;text-align: left;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">{{scope.row.lsName?scope.row.lsName:'无'}}</p>
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width" v-if="tableButtonType">
          <template slot-scope="scope">
            <div class="button-box">
              <p class="table-min-button" v-hasPermi="['chemical:hxpapply:query']"
                 v-show="(scope.row.approvalStatus == 2 || scope.row.approvalStatus == 3) && scope.row.myDataType" style="margin-right:10px;" @click="pageToggle(5,scope.row)">编辑</p>
              <p class="table-min-button" v-hasPermi="['chemical:revokeApplytask:edit']"
                 v-show="scope.row.myDataType && !scope.row.lsName && scope.row.approvalStatus == 0" style="margin-right:10px;" @click="approvalRevoke(scope.row)">撤销</p>
              <p class="table-min-button" v-hasPermi="['chemical:hxpapplyaudit:query']"
                 v-show="scope.row.approvalType == 1" style="margin-right:10px;" @click="pageToggle(6,scope.row)">审批</p>
              <p class="table-min-button" v-hasPermi="['chemical:hxpapply:query']"
                 style="margin-right:10px;" @click="pageToggle(7,scope.row)">审批单</p>
              <p class="table-min-button" v-hasPermi="['chemical:hxpapply:remove']"
                 v-show="(scope.row.approvalStatus == 2 || scope.row.approvalStatus == 3) && scope.row.myDataType" @click="delHxpapply(scope.row)">删除</p>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex;height:32px;margin-top:15px;">
        <!--<p style="flex:4;"></p>-->
        <p style="text-align: left;margin:0;line-height:32px;margin-right:20px;font-size:14px;color:#999;">
          <i class="el-icon-warning" style="color:#0183FA;"></i>
          已选择 {{selectedNum}} 项
        </p>
        <div style="flex:5;">
          <pagination :page-sizes="[20, 30, 40, 50]"
            v-show="total>0"
            :total="total"
            style="margin:0;"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </div>
    <draft-Page v-if="pageType == 2"></draft-Page>
    <list-Page :listPagePropsData="listPagePropsData" v-if="pageType == 3"></list-Page>
    <approval-page :approvalPagePropsData="approvalPagePropsData" v-if="pageType == 4"></approval-page>
    <edit-page :editPagePropsData="editPagePropsData" v-if="pageType == 5"></edit-page>
  </div>
</template>

<script>
  import { getHxpapplyList,delHxpapply,approvalRevoke,getHxpapply } from "@/api/medicUniversity-3_1/index";
  import draftPage from "./draftPage.vue"
  import listPage from "./listPage.vue"
  import approvalPage from "./approvalPage.vue"
  import editPage from "./editPage.vue"
  export default {
    name: "index",
    components: {
      draftPage,
      listPage,
      approvalPage,
      editPage
    },
    data(){
      return{
        tableButtonType:this.hasPermiDom([
          'chemical:hxpapply:query',
          'chemical:revokeApplytask:edit',
          'chemical:hxpapplyaudit:query',
          'chemical:hxpapply:query',
          'chemical:hxpapply:remove',]),
        // 传参数据
        listPagePropsData:{},
        approvalPagePropsData:{},
        editPagePropsData:{},
        //页面状态
        pageType:1,
        // 申请时间
        dateRangeOne:[],
        // 完成时间
        dateRangeTwo:[],
        // 搜索数据
        queryParamsData:{
          pageNum:1,
          pageSize:20,
        },
        // 搜索实际发送数据
        queryParams:{
          pageNum:1,
          pageSize:20,
        },
        //数据数量
        total:0,
        //数据数组
        tableList:[],
        // 选中用户组
        ids: [],
        // 非多个禁用
        multiple: true,
        //表格扩展选择器---需要在@selection-change绑定的方法内监控selection数组长度
        selectedNum:0,
      }
    },
    created() {

    },
    mounted(){
      this.getList();
    },
    methods: {
      //操作
      pageToggle(type,row){
        if(type == 0){
          //返回列表
          this.pageType = 1;
        }else if(type == 1){
          //返回列表重置搜索项
          this.pageType = 1;
          this.resetQuery();
        }else if(type == 2){
          //去草稿箱
          this.pageType = 2
        }else if(type == 3){
          //新增-去选择列表
          this.pageType = 3
        }else if(type == 4){
          //查看详情
          this.pageType = 4
        }else if(type == 5){
          //编辑
          getHxpapply(row.id).then(response => {
            let maxObj = {
              id:row.id,
              subId:parseInt(response.data.subId),
              applyReason:response.data.applyReason,
              maxList:[],
            }
            for(let i=0;i<response.data.actHxpapplyDetailList.length;i++){
              let num = 0;
              for(let o=0;o<maxObj.maxList.length;o++){
                if(maxObj.maxList[o].chemicalId == response.data.actHxpapplyDetailList[i].chemicalId){
                  num++
                }
              }
              if(num == 0){
                let obj = {
                  chemicalId:parseInt(response.data.actHxpapplyDetailList[i].chemicalId),
                  chemicalName:response.data.actHxpapplyDetailList[i].chemicalName,
                  list:[],
                }
                maxObj.maxList.push(obj);
              }
            }
            for(let i=0;i<response.data.actHxpapplyDetailList.length;i++){
              for(let o=0;o<maxObj.maxList.length;o++){
                if(maxObj.maxList[o].chemicalId == response.data.actHxpapplyDetailList[i].chemicalId){
                  let minObj = {
                    cabinetId:parseInt(response.data.actHxpapplyDetailList[i].cabinetId),
                    applyNum:parseInt(response.data.actHxpapplyDetailList[i].applyNum),
                    applyText:response.data.actHxpapplyDetailList[i].remainingStorage,
                  };
                  maxObj.maxList[o].list.push(minObj);
                }
              }
            }
            this.$set(this,'editPagePropsData',maxObj);
            this.pageType = 5;
          });
        }else if(type == 6){
          //审批
          let obj = {
            id:row.id,
            type:1,
            userType:row.userType,
            myDataType:row.myDataType
          };
          this.$set(this,'approvalPagePropsData',obj);
          this.pageType = 4;
        }else if(type == 7){
          //审批单
          let obj = {
            id:row.id,
            type:2,
            userType:row.userType,
            myDataType:row.myDataType
          };
          this.$set(this,'approvalPagePropsData',obj);
          this.pageType = 4;
        }
      },
      //撤销
      approvalRevoke(row){
        let self = this;
        this.$confirm('是否确认撤销?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          approvalRevoke({taskId:row.id}).then(response => {
            self.msgSuccess(response.msg);
            self.resetQuery();
          });
        }).then(() => {
        }).catch(() => {});
      },
      //删除
      delHxpapply(row){
        let self = this;
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          delHxpapply(row.id).then(response => {
            self.msgSuccess(response.msg);
            self.resetQuery();
          });
        }).then(() => {
        }).catch(() => {});
      },
      //获取数据列表
      getList(){
        this.queryParamsData = JSON.parse(JSON.stringify(this.queryParams));
        if(this.dateRangeOne[0]){
          this.queryParamsData.beginCreateTime = this.dateRangeOne[0];
          this.queryParamsData.endCreateTime = this.dateRangeOne[1];
        }else {
          this.queryParamsData.beginCreateTime = null
          this.queryParamsData.endCreateTime = null
        }
        if(this.dateRangeTwo[0]){
          this.queryParamsData.beginOverTime = this.dateRangeTwo[0];
          this.queryParamsData.endOverTime = this.dateRangeTwo[1];
        }else {
          this.queryParamsData.beginOverTime = null
          this.queryParamsData.endOverTime = null
        }
        getHxpapplyList(this.queryParamsData).then(response => {
          let userId = localStorage.getItem('userId')
          this.total = response.total;
          for(let i=0;i<response.rows.length;i++){
            if(response.rows[i].userId == userId){
              response.rows[i].myDataType = true;
            }
            response.rows[i].lsName = "";
            response.rows[i].dqName = "";
            for(let o=0;o<response.rows[i].historyUserList.length;o++){
              if( response.rows[i].historyUserList[o].id == userId){
                if(o == 0){
                  response.rows[i].lsName = response.rows[i].lsName + '我';
                }else{
                  response.rows[i].lsName = response.rows[i].lsName + '、我';
                }
              }else{
                if(o == 0){
                  response.rows[i].lsName = response.rows[i].lsName + response.rows[i].historyUserList[o].name;
                }else{
                  response.rows[i].lsName = response.rows[i].lsName + '、' + response.rows[i].historyUserList[o].name;
                }
              }
            }
            for(let o=0;o<response.rows[i].currentUserList.length;o++){
              if( response.rows[i].currentUserList[o].id == userId){
                if(o == 0){
                  response.rows[i].dqName = response.rows[i].dqName + '我';
                }else{
                  response.rows[i].dqName = response.rows[i].dqName + '、我';
                }
                response.rows[i].approvalType = 1;
                response.rows[i].userType = 1;
              }else{
                if(o == 0){
                  response.rows[i].dqName = response.rows[i].dqName + response.rows[i].currentUserList[o].name;
                }else{
                  response.rows[i].dqName = response.rows[i].dqName + '、'+ response.rows[i].currentUserList[o].name;
                }
              }

            }
          }
          this.tableList = response.rows;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParamsData.pageNum = 1;
        this.queryParamsData.pageSize = 20;
        this.queryParams = JSON.parse(JSON.stringify(this.queryParamsData));
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.$set(this,'queryParamsData',{});
        this.$set(this,'queryParams',{});
        this.$set(this,'dateRangeOne',[]);
        this.$set(this,'dateRangeTwo',[]);
        this.handleQuery();
      },
      /** 当前时间 */
      getCurrentTime () {
        const yy = new Date().getFullYear()
        const mm = new Date().getMonth() + 1
        const dd = new Date().getDate()
        const hh = new Date().getHours()
        const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
        const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
        return yy + '-' + mm + '-' + dd
      },
      /** 导出按钮操作 */
      exportButton(item) {
        let self = this;
        let currentDate = this.getCurrentTime()
        if(item.command == 1){
          self.$confirm(`确认导出全部数据?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(async () => {
            self.download('/chemical/hxpapply/export/', {...self.queryParamsData}, '采购申请-'+currentDate+'.xlsx')
          }).catch(() => {})
        }else if(item.command == 2){
          if(self.ids.length>0) {
            self.$confirm(`确认导出选中数据?`, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(async () => {
              let ids = self.ids.join(',');
              let obj = {
                ids :ids
              }
              console.log("obj",obj)
              self.download(`/chemical/hxpapply/export/`,obj, '采购申请-'+currentDate+'.xlsx')
            }).catch(() => {})
          }else {
            this.msgError('请选择要导出的数据')
          }
        }
      },
      /*下载失败列表*/
      failureExcel(){
        this.download('/chemical/hxpChemical/importErrorData', {}, `失败报表.xlsx`)
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.selectedNum = selection.length;
        this.ids = selection.map(item => item.id)
        this.multiple = !selection.length
      },
      /*===记录勾选数据===
        需要再el-table 添加  :row-key="getRowKeys"
        需要在selection 添加 :reserve-selection="true"
      */
      getRowKeys(row) {
        return row.id
      },
    }
  }
</script>

<style scoped lang="scss">
  .purchaseRequisition{
    flex:1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    font-weight:500;
    p{
      margin:0;
      padding:0;
    }
    .purchaseRequisition-page{
      flex:1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding:20px;
      .form-box{
        .form-dropdown-box{
          display: flex;
          margin:0;
          padding:0 10px;
          cursor: pointer;
          height:40px;
          img:nth-child(1){
            width:16px;
            height:16px;
            margin-top:12px;
          }
          p{
            width:47px;
            text-align: center;
            font-size:14px;
            margin:0;
            line-height:40px;
          }
          img:nth-child(3){
            width:10px;
            height:6px;
            margin-top:17px;
          }
        }
      }
      .button-box{
        display: flex;
      }
    }
  }
</style>
