<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <search-bar
      :formConfigs="formConfig"
      ref="searchBarForm"
      @headBtnClick="buttonClick"
    />
    <!-- 列表 -->
    <base-table
      :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-group-add ref="orderGroupAdd" @successSubmit="successSubmit" />
    </base-dialog>
    <!-- 查看详情 -->
    <!-- 新增工单 -->
    <base-dialog
      dialogTitle="绑定厂务订单"
      :dialogVisible="bindOrderVisible"
      @cancel="bindOrderCancel"
      @confirm="bindOrderConfirm"
      :before-close="bindOrderCancel"
      width='60%'
    >
      <bind-order ref="bindOrder" @bindOrderSubmit="bindOrderSubmit" />
    </base-dialog>
  </div>
</template>
<script>
import { parseTime } from '@/utils/ruoyi'
import { getOrderGroupPage, groupOrderStatusSet } from '@/api/base/orderGroup'
import { customerList } from '@/api/base/orderManage'
import OrderGroupAdd from './components/orderGroupAdd'
import BindOrder from './components/bindOrder'
import { publicFormatter } from '@/utils/dict'
const tableProps = [
  {
    prop: 'createTime',
    label: '添加时间',
    filter: parseTime,
    minWidth: 160
  },
  {
    prop: 'name',
    label: '订单名称',
    minWidth: 140,
    showOverflowtooltip: true
  },
  {
    prop: 'code',
    label: '订单编码',
    minWidth: 150
  },
  {
    prop: 'customerId',
    label: '客户',
    showOverflowtooltip: true
  },
  {
    prop: 'status',
    label: '订单状态',
    filter: publicFormatter('order_status')
  },
  {
    prop: 'productName',
    label: '产品名称',
    minWidth: 200,
    showOverflowtooltip: true
  },
  {
    prop: 'specifications',
    label: '产品规格',
    minWidth: 120,
    showOverflowtooltip: true
  },
  {
    prop: 'unit',
    label: '单位',
    filter: publicFormatter('unit_dict')
  },
  {
    prop: 'planQuantity',
    label: '计划加工量',
    width: 100
  },
  {
    prop: 'actualquantity',
    label: '实际加工量',
    width: 100
  },
  {
    prop: 'deliveTime',
    label: '交货时间',
    filter: parseTime,
    minWidth: 160
  },
  {
    prop: 'packReq',
    label: '包装要求',
    // filter: publicFormatter('pack_spec'),
    minWidth: 120,
    showOverflowtooltip: true
  },
  {
    prop: 'orderIdNum',
    label: '订单数量'
  }  
]
export default {
  name: 'OrderGroup',
  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-group:create') ? 'separate' : '',
        },
        {
          type: this.$auth.hasPermi('base:order-group:create') ? 'button' : '',
          btnName: '新增',
          name: 'add',
          color: 'success',
          plain: true
        }
      ],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 20,
        name: null,
        status: null,
        planFinishTime: []
      },
      total: 0,
      tableProps,
      list: [],
      tableH: this.tableHeight(260),
      tableBtn: [
      this.$auth.hasPermi('base:order-group:bind')
          ? {
              type: 'bind',
              btnName: '绑定',
              showTip: '厂务订单',
              showParam: {
                type: '&',
                data: [
                  {
                    type: 'less',
                    name: 'status',
                    value: 3
                  }
                ]
              }
            }
          : undefined,
      this.$auth.hasPermi('base:order-group:complete')
          ? {
              type: 'complete',
              btnName: '完成',
              showTip: '完成订单',
              showParam: {
                type: '&',
                data: [
                  {
                    type: 'equal',
                    name: 'status',
                    value: 3
                  }
                ]
              }
            }
          : undefined,
          this.$auth.hasPermi('base:order-group:termination')
          ? {
              type: 'termination',
              btnName: '终止',
              showTip: '终止',
              showParam: {
                type: '&',
                data: [
                  {
                    type: 'equal',
                    name: 'status',
                    value: 3
                  }
                ]
              }
            }
          : undefined,
          this.$auth.hasPermi('base:order-group:cancel')
          ? {
              type: 'cancel',
              btnName: '作废',
              showTip: '作废',
              showParam: {
                type: '&',
                data: [
                  {
                    type: 'less',
                    name: 'status',
                    value: 2
                  }
                ]
              }
            }
          : undefined,
          {
            type: 'detail',
            btnName: '详情'
          },
        this.$auth.hasPermi('base:order-group:edit')
          ? {
              type: 'edit',
              btnName: '编辑',
              showParam: {
                type: '&',
                data: [
                  {
                    type: 'less',
                    name: 'status',
                    value: 2
                  }
                ]
              }
            }
          : undefined
      ].filter((v) => v),
      addOrEditTitle: '',
      centervisible: false,
      priorityList: this.getDictDatas(this.DICT_TYPE.ORDER_PRIORITY),
      workIssueTitle: '',
      bindOrderVisible: false,
      orderDetailVisible: false
    }
  },
  components: { OrderGroupAdd, BindOrder },
  created() {
    window.addEventListener('resize', () => {
      this.tableH = this.tableHeight(260)
    })
    this.getList()
  },
  methods: {
    getList() {
      getOrderGroupPage({...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
                  }
                }
              })
              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.planFinishTime[0] = val.timeVal[0] + ' 00:00:00'
          this.queryParams.planFinishTime[1] = val.timeVal[1] + ' 23:59:59'
        } else {
          this.queryParams.planFinishTime = []
        }
        this.getList()
      } else {
        this.addOrEditTitle = '新增'
        this.centervisible = true
        this.$nextTick(() => {
          this.$refs.orderGroupAdd.init()
        })
      }
    },
    handleClick(val) {
      console.log(val)
      switch (val.type) {
        case 'edit':
          this.addOrEditTitle = '编辑'
          this.centervisible = true
          this.$nextTick(() => {
            this.$refs.orderGroupAdd.init(val.data.id)
          })
          break
        case 'cancel':
          this.handleEditStatus(val.data, '作废', '6')
          break
        case 'detail':
          this.$router.push({path: '/order/base/order-group/order-group-detail-data?orderGroupId='+ val.data.id})
          break
        case 'termination':
          this.handleEditStatus(val.data, '终止', '5')
          break
        case 'bind':
          this.workIssueTitle = '绑定工单'
          this.bindOrderVisible = true
          this.$nextTick(() => {
            this.$refs.bindOrder.init(val.data)
          })
          break
        case 'complete':
          this.handleEditStatus(val.data, '完成', '4')
          break
        default:
      }
    },
    // 完成,终止，作废
    handleEditStatus(val, tip, status) {
      let _this = this
      if (val.orderIdNum > 0) {// 有下级订单
        _this.$confirm('是否将"'+tip+'"操作同步至下级订单和工单?','确认信息', {
          type: 'warning',
          distinguishCancelAndClose: true,
          confirmButtonText: '同步',
          cancelButtonText: '不同步'
        }).then(function() {
          console.log('同步')
          groupOrderStatusSet({ id: val.id, status: status, isSync: true}).then(() => {
            _this.getList();
            _this.$modal.msgSuccess("操作成功");
          })
        }).catch(action => {
          if (action === 'cancel') {
            console.log('不同步')
            groupOrderStatusSet({ id: val.id, status: status, isSync: false}).then(() => {
              _this.getList();
              _this.$modal.msgSuccess("操作成功");
            })
          }else {
            return console.log('关闭')
          }
        })
      }else{// 无下级订单
        _this.$modal.confirm('是否确认"'+tip+'"集团订单名称为"' + val.name + '"的数据项?').then(function() {
          return groupOrderStatusSet({ id: val.id, status: status})
        }).then(() => {
          _this.getList();
          _this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      }
    },
    handleCancel() {
      this.$refs.orderGroupAdd.formClear()
      this.centervisible = false
      this.addOrEditTitle = ''
    },
    handleConfirm() {
      this.$refs.orderGroupAdd.submitForm()
    },
    successSubmit() {
      this.handleCancel()
      this.getList()
    },
    // 下发新增
    bindOrderCancel() {
      this.$refs.bindOrder.formClear()
      this.bindOrderVisible = false
    },
    bindOrderConfirm() {
      this.$refs.bindOrder.bindOrderSubmit()
    },
    bindOrderSubmit() {
      this.bindOrderCancel()
      this.getList()
    }
  }
}
</script>