<template>
  <div class="requisition" v-loading="failLoad">
    <div class="applyList" v-if="isList">
     
      <el-card>

      <el-super-search
        v-model="params"
        :size="size"
        :dict="dict"
        :columns="SearchColumns"
        @reset="reset"
        @submit="getList"
      ></el-super-search>

      <el-row :gutter="10" class="mb10" type="flex" justify="end" style="margin-top: 15px;">
        <el-col :span="1.5">
          <el-button type="primary" :size="size" plain @click="newAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button :size="size" :disabled="checkedList.length != 1" @click="handleCopy">复制</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" :size="size" plain
                     @click="download('/system/apply/material/download',{},'申请单模板.xlsx')">模板下载
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button :size="size" @click="handleImport">批量导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button :size="size" @click="handleBatchSubmit">批量提交</el-button>
        </el-col>
        <!-- 导入弹窗 -->
        <el-dialog 
          title="批量导入" 
          :visible.sync="importData.show" 
          width="35%" 
          center
          :before-close="handlefileDialogColse"
        >
          <div class="mb-import">
            <el-upload 
              accept=".xls, .xlsx" 
              ref="upload" 
              action="#" 
              :on-remove="handleFileRemove"
              :file-list="importData.list" 
              :auto-upload="false" 
              :on-change="handleChangeFile" 
              :limit="1"
              style="text-align: center;"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传Excel文件</div>
            </el-upload>

          </div>
          <span slot="footer">
        <el-button @click="handleImportData('cancal')">取 消</el-button>
        <el-button type="primary" @click="handleImportData('confirm')">确 定</el-button>
      </span>
        </el-dialog>
      </el-row>

      <div style="height: 600px;display: flex;">
        <el-super-table
          v-model="tableList"
          :dict="dict"
          :columns="TableColumns"
          :size="size"
          pagination
          index
          checkbox
          convenitentOperation
          :page="pageStatus"
          @pagination="getList"
          @row-dblclick="check"
          @selection-change="handleSelectionChange"
          @select="handleSelect"
        >
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="180"
          >
            <template slot-scope="scope">
              <el-button 
                type="text" 
                :size="size" 
                @click="check(scope.row)"
              >查看</el-button>
              <el-button 
                @click="edit(scope.row)" 
                v-if="scope.row.status == 0 || scope.row.status == 3" 
                type="text"
                :size="size"
              >编辑</el-button>
              <el-button 
                @click="jumpFlow(scope.row)" 
                v-if="scope.row.oaId && scope.row.oaId !=''" 
                type="text"
                :size="size"
              >流程跳转</el-button>
              <el-button 
                type="text" 
                :size="size"
                @click="deleteRow(scope.row)"
                v-if="scope.row.status == 0 || scope.row.status == 3"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-super-table>
      </div>
       

      </el-card>
    </div>

    <component 
      :is="isComponent" 
      v-model="isList" 
      :pageStu="page" 
      :disable="disable" 
      :row="rowDetail" 
      @refresh="getList"
      v-if="!isList
    "/>
  </div>
</template>

<script>
  import addReq from './add.vue';
  import {getReqList, delReq, importData, fileImport,betchSubmit,toOA} from '@/api/requisition/basic';
  import {saveAs} from "file-saver";
  import { blobValidate } from "@/utils/ruoyi";
  import { SearchColumns, TableColumns } from './columns';
  import { initDicts } from "@/utils/init.js";


  export default {
    name: 'requisition',
    dicts:[...initDicts([...SearchColumns,...TableColumns])],
    components: {
      addReq,
      ElSuperTable: () => import("@/components/super-table/index.vue"),
      ElSuperSearch: () => import("@/components/super-search/index.vue"),
    },
    data() {
      const params = this.$init.params(SearchColumns);
      return {
        failLoad: false,
        tableList: [],
        size:'mini',
        params:params,
        SearchColumns:SearchColumns,
        TableColumns:TableColumns,
        pageStatus: { pageNum: 1, pageSize: 10, total: 0 },
        queryParams: {
          billCode: '',
          name: '',
          status: '',
          pageNum: 1,
          pageSize: 10
        },
        options: [{
          value: 0, label: '未提交'
        }, {
          value: 1, label: '审批中'
        }, {
          value: 2, label: '已完成'
        }, {
          value: 3, label: '已驳回'
        },],
        total: 0,
        // isComponent
        isComponent: 'addReq',
        isList: true,
        // 页面状态
        page: '',
        rowDetail: {},
        disable: false,
        checkedList: [],
        importData: {
          show: false,
          list: []
        },
      }
    },
    created() {

    },
    mounted() {
      this.getList(this.queryParams)
    },
    methods: {
      // 批量提交
      async handleBatchSubmit(){
          let filterList = this.checkedList.filter(item => !(item.status == '0' || item.status == '3') )
          
          if(!filterList.length &&  this.checkedList.length){  

            try {

              this.failLoad = true;
              
              let ids = this.checkedList.map( item => Number(item.id));
              
              let {code,msg} = await betchSubmit(ids);

              if(code == 200){
                this.reset();
              }

              this.$notify({
                title: code == 200 ? msg : 'error',
                type: code == 200 ? 'success' :'error',
                message: code == 200 ?'' :msg,
              });

              // if(code == 200){
              //   this.$notify.success({
              //     title: msg,
              //   });
              // }else{
              //   this.$notify.error({
              //     title: '错误',
              //     message: msg,
              //   });
              // }

            } catch (error) {
              
            }finally{
              this.failLoad = false;
            }

          }else{
            this.$notify.warning({
              title: '警告',
              message: '存在不符合提交条件数据或未选择数据!',
            });
          }
      },

      async jumpFlow (row){

        const {name} = this.$store.state.user;

        try {

          let {code,msg,oaUrl} = await toOA(name,row.id);

          if(code == 200){
            window.open(oaUrl)
          }
          
        } catch (error) {
          
        }finally{

        }
      },

      reset() {
        // this.queryParams.billCode = ''
        // this.queryParams.name = ''
        // this.queryParams.status = ''
        // this.queryParams.pageNum = 1
        this.pageStatus.pageNum = 1;
        this.pageStatus.pageSize = 10;
        this.params = this.$init.params(SearchColumns);
        this.getList(this.queryParams)
      },
      newAdd() {
        this.isList = false
        this.isComponent = 'addReq'
        this.page = 'add'
        this.disable = false
      },
      // 复制
      handleCopy() {
        this.isList = false;
        this.isComponent = 'addReq';
        this.page = 'copy';
        this.rowDetail = this.checkedList[0];
        this.disable = false;
      },
      // 导入
      handleImport() {
        this.importData.show = true
      },
      // 删除文件
      handleFileRemove(file, fileList) {
        console.log('删除文件', file, 'file', fileList, 'fileList');
        this.importData.list = fileList;
      },
      // 文件发生改变
      handleChangeFile(file, fileList) {
        this.importData.list = fileList;
      },
      // 导入弹窗操作
      handleImportData(type) {
        switch (type) {
          // 取消
          case 'cancal':
            this.importData.list = [];
            this.importData.show = false;
            break;
          // 确认
          case 'confirm':
            if (this.importData.list.length) {

              let formData = new FormData();

              formData.append('file', this.importData.list[0].raw);
              importData(formData).then(res => {
                if (res.code == 200) {
                  this.importData.show = false;
                  this.importData.list = [];
                  if (res.data.flag) {
                    this.failLoad = true;
                    console.log(res.data.datas)
                    let param = {failDatas: res.data.datas}
                    if (null != param) {

                      fileImport(param).then(res => {
                        console.log('res',res)
                        const isBlob = blobValidate(res);
                        if (isBlob) {
                          const blob = new Blob([res]);
                          saveAs(blob, '导入失败的物料申请单数据.xlsx');
                        }
                        this.failLoad = false;
                      })
                    }
                  }
                  this.$message({
                    message: res.data.msg,
                    type: res.data.flag ? 'warning' : 'success'
                  });
                } else {
                  this.$message({
                    message: res.msg,
                    type: res.code == 200 ? 'success' : 'warning'
                  });
                }
              })
            } else {
              this.$message({
                message: '请上传文件之后在确认!',
                type: 'warning'
              });
            }
            break;
        }
      },
      handlefileDialogColse(done){
        this.importData.list = [];
        done();
      },
      // Select框
      handleSelect(selection, row) {

        this.checkedList = selection;

        console.log(this.checkedList, 'this.checkedList');

      },
      getList(val) {
        console.log('val', val)
        
        getReqList({...this.params,...this.pageStatus}).then(res => {
          if (res.code === 200) {
            this.tableList = res.rows;
            // this.total = res.total;
            this.pageStatus.total = res.total;
          }
        })
        this.checkedList = [];
      },
      // 表格内状态栏判断值
      statusJug(row) {
        if (row.status == 0) {
          return '未提交'
        } else if (row.status == 1) {
          return '审批中'
        } else if (row.status == 2) {
          return '已完成'
        } else if (row.status == 3) {
          return '已驳回'
        }
      },
      //
      handleSelectionChange(selection) {
        this.checkedList = selection;
      },
      check(row) {
        console.log('查看详情', row)
        this.isList = false
        this.isComponent = 'addReq'
        this.page = 'check'
        this.rowDetail = row
        this.disable = true
      },
      edit(row) {
        console.log('修改先加载详情', row)
        this.isList = false
        this.isComponent = 'addReq'
        this.page = 'edit'
        this.rowDetail = row
        this.disable = false
      },
      commit(row) {
        console.log('row', row)
      },
      deleteRow(row) {
        this.$confirm('是否删除此条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delReq(row.id).then(res => {
            if (res.code === 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              });
              this.getList(this.queryParams)
            }
          })
        }).catch(() => {
        })
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.queryParams.pageSize = val
        this.getList(this.queryParams)
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.queryParams.pageNum = val
        this.getList(this.queryParams)
      }
    }
  }
</script>

<style scoped lang="scss">
  .requisition {
    // height: calc(100vh - 84px);
    padding: 12px;
    box-sizing: border-box;
  }
</style>