<!-- 采购订单修订—— 列表 -->
<script>
import { TableColumns, SearchColumns, TabColumns, SelectColumns } from "./column";
import orderApi from "@/api/business/purchase/purchase-order";
import {
  initPage,
  initParams,
  // initDicts,
} from "@/utils/init/index.js";
import {  initDicts } from "@/utils/init.js";

const allColumns = [...TableColumns, ...SearchColumns];

TabColumns.forEach(column =>{
  allColumns.push(...column.tableColumns)
})


export default {
  name: "PuchaseOrder",
  // dicts: initDicts(SelectColumns),
  dicts: [...initDicts(allColumns)],
  components: {
    AddDrawer: () => import('./add/index.vue'),
    SeeDrawer: () => import('./see/index.vue'),
    EditDrawer: () => import('./edit/index.vue'),
    PurchaseReturnDrawer: () => import('./purchaseReturn/index.vue'),
    ElSuperTable: () => import("@/components/super-table/index.vue"),
    ElSuperSearch: () => import("@/components/super-search/index.vue"),
    },
  data() {
    const initTabColumns = () => TabColumns;
    return {
      loading: false,
      tabLoading:false,
      page: { pageNum: 1, pageSize: 10, total: 0 },
      searchColumns: SearchColumns,
      params: initParams(SearchColumns),
      tableColumns: TableColumns,
      tableData: [],
      tabColumns: initTabColumns(),
      tabName: "puOrderItemList",
      tabTableDatas: {
        puOrderItemList: [],
        puOrderExecuteList: [],
      },
      checkedList: [],
      // 子表Select
      checkedTabList: [],
      // 主表点击信息
      primaryResource:{},
      timer:300,
      timeOut:null,
    };
  },
  computed: {
    $dicts: {
      get: function () {
        return this.dict.type;
      },
    },
  },
  created() {
    this.fetchList(this.params, this.page);
    // this.handleRefreshList();
  },
  methods: {
    async fetchList(data, params) {

      try {

        this.loading = true;

        params['isAsc'] = 'desc';
        
        params['orderByColumn'] = 'updateTime';
        
        const { code, msg, rows, total } = await orderApi.list(data, params);

        if (code === 200) {

          this.page.total = total;

          this.tableData = rows;
        }
      } catch (err) {
        //
      } finally {
        
        this.loading = false;

        for (const key in this.tabTableDatas) {

          this.tabTableDatas[key] = [];

        }
      }
    },
    setSelectable(){
      return true
    },
    setTabSelectable(){

      if(this.tabName === 'puOrderItemList'){
        return true
      }

      return false

    },

    // 刷新操作
    handleRefreshList() {

      this.page.pageNum = 1;

      this.page.pageSize = 10;
      console.log(this,'this-------------------');

      this.$refs.purchaseTable.$refs.superTable.clearSelection();

      for (const key in this.tabTableDatas) {
        this.tabTableDatas[key] = []
      }

      this.$refs.puOrderItemList[0].$refs.superTable.clearSelection();

      // this.checkedList = [];
              
      // this.checkedTabList = [];

      this.primaryResource = {};

      this.fetchList(this.params, this.page);
    },
    // 查询操作
    handleQueryList() {

      let {date} = this.params;

      this.params.startDate = date ? date[0] :'';

      this.params.endDate = date ? date[1] : '';

      this.fetchList(this.params, this.page);

    },
    // 重置操作
    handleResetList() {

      this.page.pageNum = 1;
      
      this.page.pageSize = 10;

      this.params = initParams(SearchColumns);

      this.fetchList(this.params, this.page);

    },
    handleTabClick() { },
    // 新增
    handleOpenAddDrawer(copyVal) {

      const { setVisible, setCopyParams } = this.$refs.addDrawerFef;

      setVisible(true,(copyVal.id && copyVal.id != '') ? true :false);

      copyVal.id && copyVal.id != '' && setCopyParams(copyVal.id);
    },
    // 复制
    handleCopy() {
      this.handleOpenAddDrawer(this.checkedList[0]);
    },
    // 查看
    async handleOpenSeeDrawer(row) {

      window.clearInterval(this.timeOut);

      const { id } = row;

      const { setVisible, fetchItem } = this.$refs.seeDrawerRef;

      await setVisible(true);

      await fetchItem(id);

    },
    // 编辑、修订
    async handleOpenEditDrawer(row) {

      const { id } = row;

      const { setVisible, fetchItem } = this.$refs.editDrawerRef;
      
      await setVisible(true);

      await fetchItem(id);
      
    },
    
    // 获取子表信息
     handleDetailsData(row) {

      
      window.clearTimeout(this.timeOut);

      this.timeOut = setTimeout(async () =>{

        try {

          this.tabLoading = true;

          this.primaryResource = row;

          this.checkedTabList = [];

          const { code, msg, data } = await orderApi.details(row.id);

          if (code === 200) {

            // 物料信息:puOrderItemList   执行结果:puOrderExecuteList
            for (const key in this.tabTableDatas) {

              this.tabTableDatas[key] = data[key];

            }

          }
        } catch (err) {}
        finally{
          this.tabLoading = false;
        }
      },this.timer)
      
    },

    // 操作提示弹窗
    handleConfirmTips(success){

      this.$confirm('是否继续此操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          success();

        }).catch(() => {        
        });
    },

    // 删除操作
    handleDeleteList(row) {
      try {
        this.loading = true;

        this.handleConfirmTips(async()=>{

          const { id } = row;

          const { code } = await orderApi.remove(id);

          if (code === 200) {

            this.handleRefreshList();

          }
        })

      } catch (err) {
        //
      } finally {
        this.loading = false;
      }
    },
    // 批量提交
    handleBatchSubmit(){

      let inconformity = this.checkedList.filter(row => !((row.status == '0' || row.status == '3') && row.isEnd === 'N'));

      if(!inconformity.length && this.checkedList.length){

        let puOrderIds = this.checkedList.map( item => Number(item.id));

        this.fetchSubmit(puOrderIds);
      
      }else{
        this.$notify({
          title: '警告',
          message: '当前选中存在不满足提交条件的数据！',
          type: 'warning'
        });
      }

      
    },
    // 提交
    handleSubmit(row) {

      let puOrderIds = [Number(row.id)];

      this.fetchSubmit(puOrderIds);

    },
    fetchSubmit(puOrderIds){

      try {

        this.handleConfirmTips(async()=>{

          this.loading = true;

          let { code } = await orderApi.submit({ puOrderIds});

          if (code == 200) {

          this.handleRefreshList();

          }

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

    // 判断“整单退回”按钮
    judgeIsAllReturn() {
      if (this.checkedList.length == 1) {

        // 非手工、状态：自由/驳回
        if (this.judgeIsOption('return',this.checkedList[0])) {
        // if (this.checkedList[0].source != 3 &&
        //     (this.checkedList[0].status == 0 || this.checkedList[0].status == 3)
        //  ) {

          return false
        }
      }
      return true;
    },
    //  整单退回
    handleAllReturn() {

      this.handleReturn(this.checkedList[0].id,[]);
      
    },
     // 判断“行退回”按钮
     judgeIsLineReturn() {

      if (this.checkedTabList.length == 1) {

        // 主信息：非手工、状态：自由/驳回
        if(this.judgeIsOption('return',this.primaryResource)){
        // if(this.primaryResource.source != 3 && 
        //   (this.primaryResource.status == 0 || this.primaryResource.status == 3) ){

          return false
        }

      }
      return true;
    },
    // 行退回
    handleLineReturn(){

      let ids = this.checkedTabList.map(checked => checked.id);

      console.log(ids,'行退回ids');

      this.handleReturn(this.primaryResource.id,ids);

    },
    // 退回接口
    handleReturn(id,documentIds){

      this.$prompt('请输入退回原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\s*\S+?/,
          inputErrorMessage: '退回原因不能为空'
        }).then(async ({ value }) => {

          let data = {

            id:Number(id),

            documentIds:documentIds.map(ids =>Number(ids)),

            baskCause: value,
            
          };

          console.log(data);

          try {

            let { code, msg } = await orderApi.documentsReturn(data);

            if (code === 200) {

              this.handleRefreshList();

            }
          } catch (error) {
            console.log(error,'error------------');
          }
        }).catch(() => {   });
    },
    // 判断是否满足整单关闭
    judgeIsAllClose() {

      if (this.checkedList.length == 1) {

        // if (this.checkedList[0].status == 0) {
        if (this.judgeIsOption('allClose',this.checkedList[0])) {
          // 未审批状态下整单关闭
          return false
        }
      }
      return true;

    },
    // 整单关闭
     handleAllClose() {
      // 未审批状态下整单关闭
      try {

        this.handleConfirmTips(async() =>{

          let puOrderIds = this.checkedList.map(order => Number(order.id));

          let { code } = await orderApi.close({ puOrderIds });

          if (code === 200) {

            this.handleRefreshList();

          }
        })
      } catch (error) { } 
    },
    // 付款协议
    async handlePaymentRequest(){
      // name:工号
      try {

        let {code,msg} = await orderApi.payRequest();

        if(code == 200){

          msg.replace(/\/n/g,'');

          let url = `uclient://start/http://172.16.100.2:8081?ssoKey=${msg}&uiloader=nc.uap.lfw.applet.PortalUILoader&nodeId=40040407`

          window.location.href = url;

        }

      } catch (error) {}
      
    },
    // 退货
    async handlePurchaseReturn(){

      const { id } = this.checkedList[0];

      const { setVisible, fetchStorage } = this.$refs.PurchaseReturnDrawerRef;

      await setVisible(true);

      await fetchStorage(id);

    },
    // 主表Select框
    handleSelect(selection, row) {

      this.checkedList = selection;

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

    },
    handleSelectionChange(selection){
      this.checkedList = selection;
    },
    // 子表Select框
    handleTabSelect(selection, row){

      this.checkedTabList = selection;

      console.log(this.checkedTabList, 'this.checkedTabList');
    },
    handleTabSelectionChange(selection){
      this.checkedTabList = selection;
    },
    // 保留两位小数，补位
    keepTwoDecimalStr(num) {

      if(num){

          const result = Number(num.toString().match(/^\d+(?:\.\d{0,2})?/));

          let s = result.toString();

          let rs = s.indexOf('.');

          if (rs < 0) {

            rs = s.length;

            s += '.';

          }
          while (s.length <= rs + 2) {

            s += '0';

          }

          return s;

      }else{

        return '';

      }
    },
    judgeIsOption(type,source){
      // status: 0=自由态，1=审批中，2=已审核，3=已驳回 4=提交中
      // source: 1=自动协议直采，2=协议直采，3=手工
      // isEnd:整单关闭标识
      switch(type){
        case 'edit':
          return (source.status == '0' || source.status == '3') && source.isEnd === 'N';
        case 'revise':
            return source.status == '2' && source.isEnd === 'N';
        case 'del':
          return (source.status == '0' || source.status == '3') && source.source == '3' && source.isEnd === 'N';
        case 'submit':
          return (source.status == '0' || source.status == '3') && source.isEnd === 'N';
        case 'allClose':
          return source.status == 0 && source.isEnd === 'N';
        case 'return':
          return source.source != 3 && source.isEnd === 'N' &&
                (source.status == 0 || source.status == 3);
        default:
         return false;
      }
    }
  }
};
</script>

<template>
  <el-card 
    v-loading="loading" 
    style="width: calc(100% - 24px); height: 100%; margin: 10px;padding: 10px;" 
    :body-style="{ padding: 0 }"
  >
    <SeeDrawer ref="seeDrawerRef"></SeeDrawer>
    <AddDrawer ref="addDrawerFef" @close="handleRefreshList"></AddDrawer>
    <EditDrawer ref="editDrawerRef" @close="handleRefreshList"></EditDrawer>
    <PurchaseReturnDrawer ref="PurchaseReturnDrawerRef" @close="handleRefreshList"></PurchaseReturnDrawer>

    <el-super-search
      v-model="params"
      :size="'mini'"
      :dict="dict"
      :columns="searchColumns"
      @reset="handleResetList"
      @submit="handleQueryList"
    ></el-super-search>
  
    <!-- 操作 -->
    <el-row :gutter="24" type="flex" justify="end" style="margin: 20px 0;">
      <el-col :span="24" style="text-align: right;">
        <el-button size="mini" type="primary" @click="handleOpenAddDrawer"
          v-hasPermi="['material:order:add']">新增</el-button>
       
        <el-button-group style="margin-left: 10px">
          <el-button type="primary" size="mini" :disabled="checkedList.length != 1" @click="handleCopy">复制</el-button>
          <el-button type="primary" size="mini" @click="handleBatchSubmit">批量提交</el-button>
        </el-button-group>

        <el-button-group style="margin-left: 10px" :key="checkedList.length + 1">
          <el-button type="primary" size="mini" @click="handleAllReturn" :disabled="judgeIsAllReturn()">整单退回</el-button>
          <el-button type="primary" size="mini" @click="handleAllClose" :disabled="judgeIsAllClose()">整单关闭</el-button>
        </el-button-group>

        <el-button-group style="margin:0 10px">
          <!-- <el-button size="mini" 
            :disabled="!(checkedList.length == 1 && checkedList[0].deliveryStatus == '0')"
            :key="checkedList.length"
            @click="handlePurchaseReturn"
          >采购退货</el-button> -->
          <el-button type="primary" size="mini" @click="handlePaymentRequest">付款申请</el-button>

        </el-button-group>


      </el-col>
    </el-row>

    <el-super-table
      class="purchaseTable"
      v-model="tableData"
      ref="purchaseTable"
      :dict="dict"
      :columns="tableColumns"
      :selectable="setSelectable"
      index
      checkbox
      pagination
      :page="page"
      convenitentOperation
      @pagination="fetchList(params, page)"
      @row-dblclick="handleOpenSeeDrawer" 
      @row-click="handleDetailsData" 
      @selection-change="handleSelectionChange"
      @select="handleSelect"
    >
      
      <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button 
              v-if="judgeIsOption('revise',scope.row)"
              type="text" 
              size="small" 
              @click.stop="handleOpenEditDrawer(scope.row)"
              v-hasPermi="['material:order:edit']">
            修订
            </el-button>
            <el-button 
              v-if="judgeIsOption('edit',scope.row)"
              type="text" 
              size="small" 
              @click.stop="handleOpenEditDrawer(scope.row)"
              v-hasPermi="['material:order:edit']">
            编辑
            </el-button>
            <!-- 0=自由态，1=审批中，2=已审核，3=已驳回 4=提交中-->
            <el-button 
              v-if="judgeIsOption('del',scope.row)" 
              type="text" 
              size="small" 
              @click.stop="handleDeleteList(scope.row)"
              v-hasPermi="['material:order:remove']"
            >删除</el-button>
            <el-button 
              v-if="judgeIsOption('submit',scope.row)" 
              type="text" 
              size="mini"
              v-hasPermi="['material:order:toOa']" 
              @click.stop="handleSubmit(scope.row)"
            >提交</el-button>
          </template>
      </el-table-column>
    
    </el-super-table>

    <div style="position: relative; padding-top: 10px;" v-loading="tabLoading">
      <el-row style="position: absolute; top: 30px; right: 20px;z-index: 10;">
        <el-button 
          size="mini" 
          @click="handleLineReturn"
          :disabled="judgeIsLineReturn()"
        >行退回</el-button>
      </el-row>
      <el-tabs 
        v-model="tabName" 
        @tab-click="handleTabClick" 
        style="width: 100%;padding: 20px 10px;">
        <el-tab-pane 
          v-for="(column, index) in tabColumns" 
          :key="index" 
          :label="column.title" 
          :name="column.key"
        >
          <el-super-table
            style="height: 300px;"
            v-model="tabTableDatas[column.key]"
            :ref="column.key"
            :dict="dict"
            :columns="column.tableColumns"
            :selectable="setTabSelectable"
            :checkbox="setTabSelectable()"
            convenitentOperation
            @select="handleTabSelect"
            @selection-change="handleTabSelectionChange"

          >
          </el-super-table>
         
        </el-tab-pane>
        
      </el-tabs>
      
    </div>
  </el-card>
</template>

<style lang="scss">
.purchaseTable{
  .el-table__body-wrapper{
    height: 480px;
  }
}
</style>
