<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <search-bar :formConfigs="formConfig" ref="searchBarForm" @headBtnClick="buttonClick" />
    <!-- 列表 -->
    <base-table ref="table" @row-click="handleRowClick" row-key="id"
      :tree-props="{ children: 'children'}"
      :page="queryParams.pageNo" :limit="queryParams.pageSize" :table-props="tableProps" :table-data="list"
      :max-height="tableH">
      <method-btn v-if="tableBtn.length" slot="handleBtn" :width="240" label="操作" :method-list="tableBtn"
        @clickBtn="handleClick" />
    </base-table>
    <pagination :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize" :total="total"
      @pagination="getList" />
    <!-- 新增&编辑 -->
    <base-dialog :dialogTitle="addOrEditTitle" :dialogVisible="centervisible" @cancel="handleCancel"
      @confirm="handleConfirm" :before-close="handleCancel" width='60%'>
      <order-add ref="orderAdd" @successSubmit="successSubmit" />
    </base-dialog>
    <!-- 查看详情 -->
    <!-- 新增工单 -->
    <base-dialog :dialogTitle="workIssueTitle" :dialogVisible="addWorkOrdervisible" @cancel="addWorkOrderCancel"
      @confirm="addWorkOrderConfirm" :before-close="addWorkOrderCancel" width='70%'>
      <add-work-order ref="addWorkOrder" @addWorkOrderSubmit="addWorkOrderSubmit" />
    </base-dialog>
    <base-dialog :dialogTitle="splitTitle" :dialogVisible="splitWorkOrdervisible" @cancel="splitWorkOrderCancel"
      @confirm="splitWorkOrderConfirm" :before-close="splitWorkOrderCancel" width='70%'>
      <order-split ref="splitWorkOrder" @splitWorkOrderSubmit="splitWorkOrderSubmit" />
    </base-dialog>
  </div>
</template>
<script>
import { parseTime } from '@/utils/ruoyi'
import { getOrderPage, orderDelete, customerList, orderFinish, orderVoid, orderStop } from '@/api/base/orderManage'
import OrderAdd from './components/orderAdd'
import orderSplit from './components/orderSplit'
import orderNum from './components/orderNum.vue'

import AddWorkOrder from './components/addWorkOrder'
import { publicFormatter } from '@/utils/dict'
const tableProps = [
  {
    prop: 'type',
    label: '订单类型',
    showOverflowtooltip: true
  },
  {
    prop: 'createTime',
    label: '添加时间',
    filter: parseTime,
    minWidth: 160
  },
  {
    prop: 'name',
    label: '订单名称',
    minWidth: 120,
    showOverflowtooltip: true
  },
  {
    prop: 'code',
    label: '订单编码',
    minWidth: 180
  },
  {
    prop: 'customerId',
    label: '客户',
    showOverflowtooltip: true
  },
  // {
  //   prop: 'priority',
  //   label: '优先级',
  //   filter: publicFormatter('order_priority')
  // },
  {
    prop: 'status',
    label: '订单状态',
    filter: publicFormatter('order_status')
  },
  {
    prop: 'planQuantity',
    label: '计划加工量',
    width: 100
  },
  {
    prop: 'actualQuantity',
    label: '实际加工量',
    width: 100
  },
  {
    prop: 'productName',
    label: '产品',
    showOverflowtooltip: true
  },
  {
    prop: 'deliveTime',
    label: '添加时间',
    filter: parseTime,
    minWidth: 160
  },
  {
    prop: 'workOrderNum',
    label: '工单数量',
    subcomponent: orderNum,
  }
]
export default {
  name: 'OrderManage',
  data() {
    return {
      formConfig: [
        {
          type: 'input',
          label: '订单名称',
          placeholder: '订单名称',
          param: 'name'
        },
        {
          type: 'select',
          label: '状态',
          selectOptions: this.getDictDatas(this.DICT_TYPE.ORDER_STATUS),
          labelField: 'label',
          valueField: 'value',
          param: 'status'
        },
        {
          type: 'datePicker',
          label: '时间段',
          dateType: 'daterange',
          format: 'yyyy-MM-dd',
          valueFormat: "yyyy-MM-dd",
          rangeSeparator: '-',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          param: 'timeVal',
          defaultSelect: [],
          width: 250
        },
        {
          type: 'button',
          btnName: '查询',
          name: 'search',
          color: 'primary'
        },
        {
          type: this.$auth.hasPermi('base:order-manage:create') ? 'separate' : '',
        },
        {
          type: this.$auth.hasPermi('base:order-manage:create') ? 'button' : '',
          btnName: '新增',
          name: 'add',
          color: 'success',
          plain: true
        }
      ],
      splitTitle: '拆分订单',
      splitWorkOrdervisible:false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 20,
        name: null,
        status: null,
        lastIssuedTime: []
      },
      total: 0,
      tableProps,
      list: [],
      tableH: this.tableHeight(260),
      tableBtn: [
        this.$auth.hasPermi('base:order-manage:split')
          ? {
            type: 'split',
            btnName: '拆分工单',
            showTip: '拆分工单',
            showParam: {
              type: '&',
              data: [
                {
                  type: 'unequal',
                  name: 'status',
                  value: 5
                },
                {
                  type: 'equal',
                  name: 'workOrderNum',
                  value: 0
                },
              ]
            }
          }
          : undefined,
      this.$auth.hasPermi('base:order-manage:addWorkOrder')
          ? {
              type: 'add',
              btnName: '新增',
              showTip: '新增工单',
              showParam: {
                type: '|',
                data: [
                  {
                    type: 'equal',
                    name: 'status',
                    value: 1
                  },
                  {
                    type: 'equal',
                    name: 'status',
                    value: 2
                  },
                  {
                    type: 'equal',
                    name: 'status',
                    value: 3
                  }
                ]
              }
            }
          : undefined,
      this.$auth.hasPermi('base:order-manage:bindWorkOrder')
          ? {
              type: 'bind',
              btnName: '绑定',
              showTip: '绑定工单',
              showParam: {
                type: '|',
                data: [
                  {
                    type: 'equal',
                    name: 'status',
                    value: 1
                  },
                  {
                    type: 'equal',
                    name: 'status',
                    value: 2
                  },
                  {
                    type: 'equal',
                    name: 'status',
                    value: 3
                  }
                ]
              }
            }
          : undefined,
      this.$auth.hasPermi('base:order-manage:bindWorkOrder')
          ? {
              type: 'complete',
              btnName: '完成',
              showTip: '完成订单',
              showParam: {
                type: '|',
                data: [
                  {
                    type: 'equal',
                    name: 'status',
                    value: 2
                  },
                  {
                    type: 'equal',
                    name: 'status',
                    value: 3
                  }
                ]
              }
            }
          : undefined,
      this.$auth.hasPermi('base:order-manage:detail')
          ? {
              type: 'detail',
              btnName: '详情'
            }
          : undefined,
        this.$auth.hasPermi('base:order-manage:edit')
          ? {
              type: 'edit',
              btnName: '编辑',
              showParam: {
                type: '&',
                data: [
                  {
                    type: 'equal',
                    name: 'triggerOrigin',
                    value: 1
                  },
                  {
                    type: 'equal',
                    name: 'status',
                    value: 1
                  }
                ]
              }
            }
          : undefined,
        this.$auth.hasPermi('base:order-manage:delete')
          ? {
              type: 'void',
              btnName: '作废',
              showParam: {
                type: '&',
                data: [
                  {
                    type: 'equal',
                    name: 'status',
                    value: 1
                  }
                ]
              }
            }
          : undefined,
        this.$auth.hasPermi('base:order-manage:stop')
          ? {
              type: 'stop',
              btnName: '终止',
              // showParam: {
              //   type: '&',
              //   data: [
              //     {
              //       type: 'equal',
              //       name: 'status',
              //       value: 1
              //     }
              //   ]
              // }
            }
          : undefined
      ].filter((v) => v),
      addOrEditTitle: '',
      centervisible: false,
      expandedRowKeys:[],
      priorityList: this.getDictDatas(this.DICT_TYPE.ORDER_PRIORITY),
      workIssueTitle: '',
      addWorkOrdervisible: false,
      orderDetailVisible: false
    }
  },
  components: { OrderAdd, AddWorkOrder,orderSplit },
  created() {
    window.addEventListener('resize', () => {
      this.tableH = this.tableHeight(260)
    })
    this.getList()
  },
  methods: {
    async handleRowClick(row) {
      console.log(row)
      if (!row.children) {
        const queryParams = {
          pageNo: this.queryParams.pageNo,
          pageSize: this.queryParams.pageSize,
          name: this.queryParams.name,
          status: this.queryParams.status,
          lastIssuedTime: this.queryParams.lastIssuedTime,
          parentId: row.id
        }
        const response = await getOrderPage(queryParams)
        // row.children = response.data.records
        this.list.forEach((ele) => {
          if (ele.id === row.id) {
        this.$set(this.list[row._pageIndex-1], 'children', response.data.records); // 展开该行
          }
        })
        row.hasChildren = true;
        this.$set(row, 'expanded', true); // 展开该行
      } else {
        row.expanded = !row.expanded; // 切换展开/折叠状态
      }
      // this.$nextTick(() => {
      //   const tableInstance = this.$refs.table.getTableRef();
      //   tableInstance.toggleRowExpansion(row);
      // })
    },
    getList() {
      getOrderPage({...this.queryParams}).then(res => {
        let arr = res.data.records || []
        this.total = res.data.total || 0
        // if (arr.length > 0) {
        //   customerList().then(result => {
        //     let tempData = result.data || []
        //     if (tempData.length > 0) {
        //       arr.map(item => {
        //         for (let i of tempData) {
        //           if (item.customerId === i.id) {
        //             item.customerId = i.name
        //           }
        //         }
        //         item.price = item.price.toFixed(2)
        //       })
              this.list = arr
        //     }
        //   })
        // }else {
        //   this.list = arr
        // }
      })
    },
    buttonClick(val) {
      console.log(val)
      if (val.btnName === 'search') {
        this.queryParams.name = val.name
        this.queryParams.status = val.status
        if (val.timeVal && val.timeVal.length > 0) {
          this.queryParams.lastIssuedTime[0] = val.timeVal[0] + ' 00:00:00'
          this.queryParams.lastIssuedTime[1] = val.timeVal[1] + ' 23:59:59'
        } else {
          this.queryParams.lastIssuedTime = []
        }
        this.getList()
      } else {
        this.addOrEditTitle = '新增'
        this.centervisible = true
        this.$nextTick(() => {
          this.$refs.orderAdd.init()
        })
      }
    },
    handleClick(val) {
      console.log(val)
      switch (val.type) {
        case 'edit':
          this.addOrEditTitle = '编辑'
          this.centervisible = true
          this.$nextTick(() => {
            this.$refs.orderAdd.init(val.data.id)
          })
          break
        case 'delete':
          this.handleDelete(val.data)
          break
        case 'detail':
          this.$router.push({path: 'order-detail-data?orderId='+ val.data.id})
          break
        case 'add':
          this.workIssueTitle = '新增工单'
          this.addWorkOrdervisible = true
          this.$nextTick(() => {
            this.$refs.addWorkOrder.init(val.data, 'add')
          })
          break
        case 'void':
          orderVoid({ id: val.data.id }).then((res) => {
            console.log(res)
          })
          break
        case 'split':
          this.splitTitle = '拆分订单'
          this.splitWorkOrdervisible = true
          this.$nextTick(() => {
            this.$refs.splitWorkOrder.init(val.data)
          })
          // orderVoid({ id: val.data.id }).then((res) => {
          //   console.log(res)
          // })
          break
        case 'bind':
          this.workIssueTitle = '绑定工单'
          this.addWorkOrdervisible = true
          this.$nextTick(() => {
            this.$refs.addWorkOrder.init(val.data, 'bind')
          })
          break
        case 'complete':
          this.handleComplete(val.data)
          break
        case 'stop':
          orderStop({ id: val.data.id }).then((res) => {
            this.getList()
          })
          break
        default:
      }
    },
    // 删除
    handleDelete(val) {
      this.$modal.confirm('是否确认删除"' + val.name + '"的数据项?').then(function() {
          return orderDelete({ id: val.id })
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
    },
    // 完成
    handleComplete(val) {
      this.$modal.confirm('是否确认完成订单"' + val.name + '"?').then(function() {
          return orderFinish({ id: val.id })
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
    },
    // 新增
    handleCancel() {
      this.$refs.orderAdd.formClear()
      this.centervisible = false
      this.addOrEditTitle = ''
    },
    handleConfirm() {
      this.$refs.orderAdd.submitForm()
    },
    successSubmit() {
      this.handleCancel()
      this.getList()
    },
    // 下发新增
    addWorkOrderCancel() {
      this.$refs.addWorkOrder.formClear()
      this.addWorkOrdervisible = false
    },
    addWorkOrderConfirm() {
      this.$refs.addWorkOrder.addWorkOrderSubmit()
    },
    addWorkOrderSubmit() {
      this.addWorkOrderCancel()
      this.getList()
    },
    splitWorkOrderCancel() {
      this.$refs.splitWorkOrder.formClear()
      this.splitWorkOrdervisible = false
    },
    splitWorkOrderConfirm() {
      this.$refs.splitWorkOrder.submitForm()
    },
    splitWorkOrderSubmit() {
      this.splitWorkOrderCancel()
      this.getList()
    }
    // bindWorkOrderCancel() {
    //   this.$refs.bindWorkOrder.formClear()
    //   this.bindWorkOrdervisible = false
    // },
    // bindWorkOrderConfirm() {
    //   this.$refs.bindWorkOrder.bindWorkOrderSubmit()
    // },
    // bindWorkOrderSubmit() {
    //   this.bindWorkOrderCancel()
    //   this.getList()
    // }
  }
}
</script>
