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


export default {
  name: "PuchaseOrder",
  dicts: initDicts(SelectColumns),
  components: {
    AddDrawer: () => import('./add/index.vue'),
    SeeDrawer: () => import('./see/index.vue'),
    EditDrawer: () => import('./edit/index.vue'),
  },
  data() {
    const initTabColumns = () => TabColumns;
    return {
      loading: false,
      isSimpleSearch: true,
      pageSizes: [10, 20, 50, 100],
      page: initPage(),
      searchColumns: SearchColumns,
      params: initParams(SearchColumns),

      tableColumns: TableColumns,
      tableData: [],
      tabColumns: initTabColumns(),
      tabName: "puOrderItemList",
      tabTableDatas: {
        puOrderItemList: [],
        puOrderExecuteList: [],
      },
      checkedList: [],
      // 子表Select
      checkedTabList: [],
      // 主表点击信息
      primaryResource:{},
      timer:300,
      timeOut:null,
    };
  },
  computed: {
    showSearchColumns() {
      return this.isSimpleSearch
        ? this.searchColumns.slice(0, 4)
        : this.searchColumns;
    },
  },
  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] = [];

        }
      }
    },
    handleSearchChange() {
      this.isSimpleSearch = !this.isSimpleSearch;
    },

    // 刷新操作
    handleRefreshList() {
      this.page = initPage();
      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 = initPage();
      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() {

      // let rowDetails = {
      //   ... this.checkedList[0],
      //   id: '',
      //   code: '',
      //   status: '0',
      //   source: '3',
      // };
      this.handleOpenAddDrawer(this.checkedList[0]);
    },
    // 查看
    async handleOpenSeeDrawer(row) {
      window.clearInterval(this.timeOut);
      const { id } = row;
      const { setVisible, fetchItem } = this.$refs.seeDrawerFef;
      await setVisible(true);
      await fetchItem(id);
    },
    // 编辑、修订
    async handleOpenEditDrawer(row) {
      const { id } = row;
      const { setVisible, fetchItem } = this.$refs.editDrawerFef;
      await setVisible(true);
      await fetchItem(id);
    },
    // 获取子表信息
     handleDetailsData(row) {
      window.clearTimeout(this.timeOut)
      this.timeOut = setTimeout(async () =>{

        try {
          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) {}
      },this.timer)
      
    },

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

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

          success();

        }).catch(() => {

          this.$message({
            type: 'info',
            message: '已取消操作!'
          });          
        });
    },

    // 删除操作
    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;
      }
    },
    // 提交
    handleSubmit(row) {

      try {

       this.handleConfirmTips(async()=>{

         let { code } = await orderApi.submit({ puOrderId: row.id });
 
         if (code == 200) {
 
          this.handleRefreshList();
 
         }

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

        // 非手工、状态：自由/驳回
        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.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) {
          // 未审批状态下整单关闭
          return false
        }
      }
      return true;

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

        this.handleConfirmTips(async() =>{

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

          // console.log(puOrderIds,'puOrderIds');
          let { code } = await orderApi.close({ puOrderIds });

          if (code === 200) {

            this.handleRefreshList();

          }
        })
      } catch (error) { } 
    },
    // 付款协议
    async handlePaymentRequest(){
      // name:工号
      try {
        // let {name} = this.$store.state.user;

        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) {
        
      }
      
    },
    // 主表Select框
    handleSelect(selection, row) {

      this.checkedList = selection;

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

    },
    // 子表Select框
    handleTabSelect(selection, row){

      this.checkedTabList = selection;

      console.log(this.checkedTabList, 'this.checkedTabList');
    },
  }
};
</script>

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

    <el-form 
      size="mini" 
      label-position="right" 
      label-width="100px" 
      :model="params" 
      style="padding: 20px 0 0 0"
    >
      <el-row :gutter="24" >
        <el-col :span="20">
          <el-row :gutter="20" style="display:flex; flex-wrap: wrap;">
            <el-col 
              v-for="column in showSearchColumns" 
              :key="column.title" 
              :xl="6" :lg="6" :md="8" :sm="12" :xs="24"
            >
              <el-form-item :prop="column.key" :label="column.title">

                <el-input v-if="column.inputType === 'Input'" 
                  v-model="params[column.key]" 
                  :placeholder="column.placeholder"
                  @keyup.enter.native="fetchList(params, page)"
                ></el-input>
                <dr-popover-select v-if="column.inputType === 'PopoverSelect'"
                  v-model="params[column.key]"
                  :source.sync="params"
                  :title="column.title"
                  :type="column.referName"
                  :multiple="column.multiple"
                  :readonly="column.readonly"
                  :value-key="column.valueKey"
                  :placeholder="column.placeholder"
                  :data-mapping="column.dataMapping"
                  :query-params="column.queryParams"
                  :clearable="column.clearable"
                  @keyup.enter.native="fetchList(params, page)"
                ></dr-popover-select>
                <!-- @keyup.enter.native="useQuery(params, page)" -->

                <el-select v-if="column.inputType === 'Select'" 
                v-model="params[column.key]" 
                :disabled="column.disabled"
                :clearable="column.clearable" 
                :placeholder="column.placeholder" 
                :multiple="column.multiple"
                :collapse-tags="column.tags"
                style="width: 100%"
                @keyup.enter.native="fetchList(params, page)"
                >
                <el-option 
                  v-for="item in dict.type[column.referName]" 
                  :key="item.value" 
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
              </el-select>
              <!-- 只有是否 -->
              <el-select v-if="column.inputType === 'SelectCheck'" 
                v-model="params[column.key]" 
                :disabled="column.disabled"
                :clearable="column.clearable" 
                :placeholder="column.placeholder" 
                style="width: 100%"
                @keyup.enter.native="fetchList(params, page)"
                >
                <el-option key="N" label="否" value="N"></el-option>
                <el-option key="Y" label="是" value="Y"></el-option>
              </el-select>

              <el-date-picker v-if="column.inputType === 'DatePicker'" 
                v-model="params[column.key]"
                size="mini"
                type="daterange"
                :value-format="column.valueFormat"
                :unlink-panels="column.unlinkPanels"
                :picker-options="column.pickerOptions"
                :range-separator="column.rangeSeparator"
                :end-placeholder="column.endPlaceholder"
                :start-placeholder="column.startPlaceholder"
                :clearable="column.clearable"
                style="width: 100%"
                @keyup.enter.native="fetchList(params, page)"
              >
              </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="4" style="text-align: right; padding-right: 40px">
          <el-button type="primary" size="mini" @click="handleQueryList"
            v-hasPermi="['material:order:query']">搜索</el-button>
          <el-button size="mini" @click="handleResetList">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-divider>
      <i :class="isSimpleSearch ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" style="cursor: pointer"
        @click="handleSearchChange"></i>
    </el-divider>

    <!-- 操作 -->
    <el-row :gutter="24" style="padding: 0 20px">
      <!-- <el-col :span="6">123</el-col> -->
      <el-col :span="24" style="text-align: right;margin: 0 10px 0 0">

        <!-- <el-button-group style="margin-left: 10px"> -->
        <el-button size="mini" type="primary" plain @click="handleOpenAddDrawer"
          v-hasPermi="['material:order:add']">新增</el-button>
        <!-- </el-button-group> -->

        <el-button-group style="margin-left: 10px">
          <el-button size="mini" :disabled="checkedList.length != 1" @click="handleCopy">复制</el-button>
        </el-button-group>

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

        <el-button-group style="margin-left: 10px">
          <!-- <el-button size="mini">采购退货</el-button> -->
          <el-button size="mini" @click="handlePaymentRequest">付款申请</el-button>

          <!-- <el-button size="mini">附件管理</el-button>
          <el-button size="mini">单据追溯</el-button> -->
        </el-button-group>
      </el-col>
    </el-row>

    <el-table 
      @row-dblclick="handleOpenSeeDrawer" 
      @row-click="handleDetailsData" 
      :data="tableData" 
      size="mini"
      highlight-current-row
      @select="handleSelect"
      height="450"
      style="width: 100%; margin: 20px 0 0 0"
    >
      <el-table-column type="selection" width="45" ></el-table-column>
      <el-table-column type="index" width="50" label="序号"></el-table-column>
      <el-table-column 
        v-for="(column, index) in tableColumns" 
        :key="index" 
        :prop="column.key" 
        :label="column.title"
        :width="column.width || 180" 
        :show-overflow-tooltip="column.showOverflowTooltip || true"
      >

        <template slot-scope="scope">
          <dict-tag v-if="column.inputType === 'Select'" 
            size="small" 
            :value="scope.row[column.key]"
            :options="dict.type[column.referName]"
           />

          <el-checkbox v-else-if="column.inputType === 'Checkbox'"
            v-model="scope.row[column.key]" 
            disabled 
            true-label="Y"
            false-label="N"
          > </el-checkbox>
          <span v-else>{{ scope.row[column.key] }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <!-- <el-button @click.stop="handleOpenSeeDrawer(scope.row)" type="text" size="small">查看</el-button> -->
          <el-button 
            v-if="scope.row.status == '2'"
            type="text" 
            size="small" 
            @click.stop="handleOpenEditDrawer(scope.row)"
            v-hasPermi="['material:order:edit']">
           修订
          </el-button>
          <el-button 
            v-if="scope.row.status == '0' || scope.row.status == '3'"
            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="(scope.row.status == '0' || scope.row.status == '3') && scope.row.source == '3'" 
            type="text" 
            size="small" 
            @click.stop="handleDeleteList(scope.row)"
            v-hasPermi="['material:order:remove']"
          >删除</el-button>
          <el-button 
            v-if="scope.row.status == '0' || scope.row.status == '3'" 
            type="text" 
            size="mini"
            v-hasPermi="['material:order:toOa']" 
            @click.stop="handleSubmit(scope.row)"
          >提交</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="page.total>0"
      :total="page.total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="fetchList(params, page)"
    />
   
    <div style="position: relative; padding-top: 10px;">
      <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-table 
            :data="tabTableDatas[column.key]" 
            style="width: 100%" 
            highlight-current-row
            :height="tabTableDatas[column.key].length ? 300 : 100"
            @select="handleTabSelect"
          >
            <el-table-column
              v-if=" tabName === 'puOrderItemList'" 
              type="selection" 
              width="45"
            ></el-table-column>
            <el-table-column type="index" width="50" label="序号"></el-table-column>
            <el-table-column 
              v-for="(cColumn, cIndex)  in column.tableColumns" 
              :key="cIndex" 
              :prop="cColumn.key"
              :label="cColumn.title" 
              :width="cColumn.width || 180"
              :show-overflow-tooltip="cColumn.showOverflowTooltip || true"
            >
              <template slot-scope="scope">
                <dict-tag v-if="cColumn.referName" 
                  size="small" 
                  :value="scope.row[cColumn.key]"
                  :options="dict.type[cColumn.referName]"
                 />
                <el-checkbox v-else-if="cColumn.inputType === 'Checkbox'" 
                  v-model="scope.row[cColumn.key]"
                  disabled
                  true-label="Y" 
                  false-label="N"
                ></el-checkbox>
                <span v-else>{{ scope.row[cColumn.key] }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
      </el-tabs>
      
    </div>
  </el-card>
</template>
