<template>
  <div>
    <basic-container v-show="!detailsOpen">
      <avue-crud :option="option" :search.sync="search" v-model="form" :table-loading="loading" :data="dataList"
        ref="crud" :key="key" @selection-change="selectionChange" @on-load="onLoad" @search-change="searchChange"
        @row-del="rowDel" @refresh-change="refreshChange"
        @resetColumn="resetColumnTwo('crud', 'option', 'optionList', 346)"
        @saveColumn="saveColumnTwo('crud', 'option', 'optionList', 346)" :page.sync="page"
        @row-update="rowUpdate">
        <template slot-scope="{type,size,row,index}" slot="menu" >
          <!--<el-button icon="el-icon-view" :size="size" :type="type" @click="check(row)">查看</el-button>-->
          <!--  :disabled="Number(row.sendTotalNum) == Number(row.goodsTotalNum)" 之前的判断是否修改的条件 -->
          <el-button type="text" size="small" :disabled="row.statusName != '待处理'" @click="rowCell(row, index)">{{ row.$cellEdit ? '保存' : '修改' }}
          </el-button>
          <!-- <el-button :disabled="row.statusName === '已派工'" :size="size" :type="type"
            @click="$refs.crud.rowDel(row, index)">删除
          </el-button> -->
        </template>
        <template slot="corpNameSearch">
          <crop-select v-model="search.corpId" corpType="KH" :refresh="false"></crop-select>
        </template>
        <template slot-scope="{type,size,row,$index}" slot="menuLeft">
          <!--  <el-button icon="el-icon-plus" type="primary" :size="size" @click="detailsOpen = true">新增</el-button>-->
          <!--  <el-button type="warning" icon="el-icon-download" size="small" @click="outExport">导出</el-button>-->
          <el-button type="success" icon="el-icon-finished" size="small" @click="dispatching"
            :disabled="selectionList.length <= 0">派工
          </el-button>

            <el-button type="success" icon="el-icon-finished" size="small" @click="shipRevokeWorkOrderfun"
                       :disabled="!chexiaofun()">撤销派工
            </el-button>
        </template>
      </avue-crud>
    </basic-container>
    <!--<detailsPage v-if="detailsOpen" :onLoad="form" :detailData="detailData" @backToList="backToList"></detailsPage>-->
  </div>
</template>

<script>
import { getList, remove, outboundWorkOrder,typeSave,shipRevokeWorkOrder } from "@/api/tirePartsMall/salesService/outboundTask";
import da from "element-ui/src/locale/lang/da";
// import detailsPage from "./detailsPage"

export default {
  name: "index",
  components: {
    // detailsPage
  },
  data() {
    return {
      detailsOpen: false,
      loading: false,
      search: {},
      form: {},
      dataList: [],
      selectionList: [],
      detailData: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      key: 0,
      option: {},
      optionList: {
        selection: true,
        viewBtn: false,
        editBtn: false,
        celBtn: true,
        delBtn: false,
        addBtn: false,
        menu: true,
        index: true,
        span: 8,
        border: true,
        height: "auto",
        searchMenuPosition: "right",
        align: "center",
        size: "small",
        menuWidth: 100,
        searchSpan: 8,
        searchIcon: true,
        searchIndex: 2,
        highlightCurrentRow: true,
        dialogWidth: "70%",
        summaryText: "合计",
        showSummary: true,
        sumColumnList: [ {
            name: 'goodsTotalNum',
            type: 'sum',
            decimals: 0
          }, {
            name: 'sendTotalNum',
            type: 'sum',
            decimals: 0
          },],
        column: [{
          label: '来源单号',
          prop: "ordNo",
          searchOrder:1,
          search: true,
          width: 140,
          overHidden: true,
        },{
            label: '单据编号',
            prop: "billno",
            searchOrder:1,
            search: true,
            width: 140,
            overHidden: true,
        }, {
            label: '状态',
            prop: "statusName",
            searchOrder:2,
            width: 100,
            search: true,
            type: 'select',
            overHidden: true,
            searchValue:'待处理',
            dicData: [{
                label: '待处理',
                value: '待处理'
            }, {
                label: '已派工',
                value: '已派工'
            },{
                label: '未完成',
                value: '未完成'
            }, {
                label: '已完成',
                value: '已完成'
            }],
        }, {
          label: '业务对象',
          prop: "customerName",
          search: true,
          width: 140,
          type: 'select',
          overHidden: true,
          props: {
            label: 'cname',
            value: 'cname'
          },
          dicUrl: '/api/blade-sales-part/corpsDesc/listAll?corpType=KH',
        }, 
          // , {
          //     label: "商品种类",
          //     prop: "corpId",
          //     width: 100,
          //     overHidden: true,
          // }
        // {
        //   label: '业务来源',
        //   prop: "bsType",
        //   width: 100,
        //   overHidden: true,
        // },
        {
          label: '来源公司',
          prop: "salesCompanyName",
          search: true,
          width: 100,
          overHidden: true,
          type: 'select',
          props: {
            label: 'fullName',
            value: 'fullName'
          },
          dicUrl: '/api/blade-system/dept/top-list'
        },
        {
          label: '发货仓库',
          prop: "storageName",
          width: 100,
          search: true,
          overHidden: true,
          cell:false,
          type: 'select',
          props: {
            label: 'cname',
            value: 'cname'
          },
          dicUrl: '/api/blade-sales-part/storageDesc/listAll',
        },
         {
          label: '库管',
          prop: "stockClerkName",
          width: 100,
          cell:false,
          overHidden: true,
          type: 'select',
          props: {
            label: 'realName',
            value: 'realName'
          },
          dicUrl: '/api/blade-user/stockClerkList',
        },
        // {
        //   label: '收货地址',
        //   prop: "recAddress",
        //   width: 200,
        //   overHidden: true,
        // },
        {
          label: '退货数量',
          prop: "sendTotalNum",
          width: 100,
          overHidden: true,
        },
        {
          label: '联系人',
          prop: "contacts",
          width: 100,
          overHidden: true,
        }, {
          label: '电话',
          prop: "phone",
          width: 100,
          overHidden: true,
        }, {
          label: '备注',
          prop: "remarks",
          width: 200,
          cell:false,
          overHidden: true,
        }, {
          label: '业务日期',
          prop: "businesDate",
          searchProp: "businesDateList",
          type: "date",
          overHidden: true,
          search: true,
          width: 100,
          searchRange: true,
          searchDefaultTime: ["00:00:00", "23:59:59"],
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss"
        }]
      }
    }
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(346), this.optionList);
    this.key++
    let i = 0;
    this.option.column.forEach(item => {
      if (item.search) i++
    })
    if (i % 3 !== 0) {
      const num = 3 - Number(i % 3)
      this.option.searchMenuSpan = num * 8;
      this.option.searchMenuPosition = "right";
    }
    this.option = await this.getColumnData(this.getColumnName(346), this.optionList);

    this.option.selectable = (row, index) => {
      return Number(row.sendTotalNum) !== Number(row.goodsTotalNum);
    }

  },
  methods: {
      // 撤销派工的数据判断
      chexiaofun(){
          let typefalse = false
          for(let item of this.selectionList) {
              if (item.statusName == '已派工') {
                  typefalse = true
              }else {

                  typefalse = false
                  break;
              }
          }
          return typefalse
      },
    selectionChange(list) {
      this.selectionList = list
    },
      // 撤销派工
      shipRevokeWorkOrderfun(){
          this.$confirm('是否要撤销派工?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(()=>{
              const data = []
              for(let i in this.selectionList) {
                  data.push(this.selectionList[i].id)
              }
              shipRevokeWorkOrder(data.join(',')).then(res=>{
                  this.$message({
                      type: 'success',
                      message: '撤销派工成功!'
                  });
                  this.onLoad(this.page)
              })
          })
      },
    dispatching() {
      this.$confirm('是否确认派工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = []
        for (let item of this.selectionList) {
          data.push(item.id)
        }
        this.loading = true; // Show the loading spinner
        outboundWorkOrder(data.join(',')).then(res => {
          this.$message({
            type: 'success',
            message: '生成成功!'
          });
          this.onLoad(this.page)
        }).finally(() => {
          this.loading = false; // Hide the loading spinner
        });
      })
    },
    check(row) {
      this.form = row
      this.detailsOpen = true
    },
    backToList(type) {
      this.form = {}
      this.detailsOpen = false
      if (type === 0) {
        this.detailData = {}
      }
      this.onLoad(this.page, this.search)
    },
    //列表更新
    rowUpdate(form, index, done) {
      console.log(form);
      typeSave(form).then(res => {
        this.$message({type: "success", message: form.id ? "修改成功!" : "新增成功!"});
        // this.page.currentPage = 1;
        // this.onLoad(this.page);
        //成功关闭此页面回到列表页
        // this.backToList()
      })
      done()
    },
    //刷新
    refreshChange() {
      this.onLoad(this.page, this.search)
    },
    rowCell(row,index){
      this.findObject(this.option.column, "storageName").cell = true
      this.findObject(this.optionList.column, "storageName").cell = true
      this.findObject(this.option.column, "stockClerkId").cell = true
      this.findObject(this.optionList.column, "stockClerkId").cell = true
      this.findObject(this.option.column, "remarks").cell = true
      this.findObject(this.optionList.column, "remarks").cell = true
      this.$refs.crud.rowCell(row, index)
    },
    rowDel(form, index) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(form.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.dataList.splice(index, 1);
          this.onLoad(this.page)
        })
      }).catch(() => {
      });
    },
    searchChange(params, done) {
      this.page.currentPage = 1
      done();
      this.onLoad(this.page, params)
    },
    onLoad(page, params = {}) {
      params = {
        // ...params,
        current: page.currentPage,
        size: page.pageSize,
        bizTypeName: "THSHRW",
          statusName:'待处理',
        ...Object.assign(params, this.search),
        customerName : params.$customerName
      }
      console.log(params);
      this.loading = true
      getList(params).then(res => {
        this.dataList = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },
    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      console.log(2132);
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      // this.option = await this.getColumnData(this.getColumnName(346), this.optionList);

      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      console.log(this[option]);
      console.log(this[optionBack]);
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
      this.option.selectable = (row, index) => {
      return Number(row.sendTotalNum) !== Number(row.goodsTotalNum);
    }
    }
  }
}
</script>

<style scoped></style>
