<!--
@name: 预约管理
@author: 张泽贤
@time: 2022-07-14
@doc:
-->
<template>
  <div class="booking pages">
    <p-spin :spinning="spinning" v-if="!editType">
      <p-card style="margin-bottom: 10px">
        <p-form-model ref="formTarget" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from">
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="预约号">
                <p-input v-model="form.appointmentNo" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="预约地点">
                <p-input v-model="form.branchName" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="预约类型">
                <p-select v-model="form.appointmentType" :options="options.APPOINTMENT_TYPE" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="预约司机">
                <p-input v-model="form.driverName" />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="车牌号">
                <p-input v-model="form.vehiclePlateNumber" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="预约电话">
                <p-input v-model="form.driverPhoneNumber" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="预约状态">
                <p-select v-model="form.status" :options="options.APPOINTMENT_STATUS" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="运单号">
                <p-input v-model="form.shipbillNo" />
              </p-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <p-form-model-item label="预约日期" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                <p-range-picker v-model="estimatedPickupTime" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="12">
              <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: right">
                <a-space>
                  <p-button type="primary" @clickSync="onSearch" icon="search" :disabled="!branchInfo.branchId">查询</p-button>
                  <p-button @click="onReset" :disabled="!branchInfo.branchId">重置</p-button>
                </a-space>
              </p-form-model-item>
            </a-col>
          </a-row>
        </p-form-model>
      </p-card>
      <p-card title="预约信息" style="margin-bottom: 10px">
        <div slot="extra">
          <p-form-model ref="ruleForm" class="plg-grid-from" :model="branchInfo" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" :rules="rules">
            <a-row>
              <a-col :span="12">
                <p-form-model-item label="仓库" prop="branchName">
                  <p-search-modal v-model="branchInfo.branchName" v-bind="$data.$formItems.parkBranchAttr" @change="(...args) => onFormChange('branch', ...args)" />
                </p-form-model-item>
              </a-col>
              <a-col :span="12">
                <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: right">
                  <a-space>
                    <p-button type="primary" @click="onAudit" :disabled="!selectedRowKeys.length || buttonDisabled">审核</p-button>
                    <p-button type="primary" @click="onAdjust" :disabled="!selectedRowKeys.length || buttonDisabled">调整</p-button>
                    <p-button type="danger" @click="onCancel" :disabled="!selectedRowKeys.length || buttonDisabled">取消</p-button>
                    <a-dropdown>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item key="2">
                            <export-button
                              type="link"
                              :ids="selectedRowKeys"
                              :pages="mainPages"
                              :getSearchValue="() => listParams"
                              downloadFileName="预约管理"
                              :allUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/booking/export_all'"
                              :currentUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/booking/export_page'"
                              :selectUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/booking/export_select_line'"
                              >导出</export-button
                            >
                          </a-menu-item>
                        </a-menu>
                      </template>
                      <a-button>更多</a-button>
                    </a-dropdown>
                  </a-space>
                </p-form-model-item>
              </a-col>
            </a-row>
          </p-form-model>
        </div>
        <t-table
          ref="masterTable"
          dragle
          bordered
          row-key="appointmentId"
          :id="$route.meta.menuId + '_booking'"
          :scroll="{ x: true }"
         :vScrollX="{enabled:true}"
        :vScrollY="{enabled:true,rows:10}"
          @selectChange="selectKey=>selectedRowKeys=selectKey"
          :columns="mx_columns"
          :data-source.sync="dataSource"
          :remote-url="listRemoteUrl"
          :remoteData="listParams"
          :rowSelectType="2"
          @clickRow="masterClickRow"
          :autoLoad="false"
          :doneBefore="doneBefore"
        >
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <a @click.stop="toAudit(record)" :disabled="record.status >= 20">审核</a>
              <a @click.stop="toAdjust(record)" :disabled="record.status >= 20">调整</a>
              <a @click.stop="toCancel(record)" :disabled="record.status >= 20">取消</a>
            </a-space>
          </template>
        </t-table>
      </p-card>
      <p-card>
        <a-tabs style="background-color: #fff">
          <a-tab-pane :key="1" tab="配载运单" :forceRender="true">
            <t-table
              ref="waybillTable"
              dragle
              bordered
              row-key="shipbillId"
              :id="$route.meta.menuId + '_waybillTable'"
              :scroll="{ x: true, y: 300 }"
              :columns="waybill_columns"
              :data-source.sync="waybillDataSource"
              :remote-url="waybillListRemoteUrl"
              :remoteData="waybillListParams"
              :rowSelectType="false"
              :autoLoad="false"
            >
            </t-table>
          </a-tab-pane>
          <a-tab-pane :key="2" tab="配载商品" :forceRender="true">
            <t-table
              ref="goodsTable"
              dragle
              bordered
              row-key="id"
              :id="$route.meta.menuId + '_goodsTable'"
              :scroll="{ x: true, y: 300 }"
              :columns="goods_columns"
              :data-source.sync="goodsDataSource"
              :remote-url="goodsListRemoteUrl"
              :remoteData="goodsListParams"
              :rowSelectType="false"
              :autoLoad="false"
            >
            </t-table>
          </a-tab-pane>
          <a-tab-pane :key="3" tab="配载包裹" :forceRender="true">
            <t-table
              ref="packTable"
              dragle
              bordered
              row-key="id"
              :id="$route.meta.menuId + '_packTable'"
              :scroll="{ x: true, y: 300 }"
              :columns="pack_columns"
              :data-source.sync="packDataSource"
              :remote-url="packListRemoteUrl"
              :remoteData="packListParams"
              :rowSelectType="false"
              :autoLoad="false"
            >
            </t-table>
          </a-tab-pane>
        </a-tabs>
      </p-card>
    </p-spin>

    <!-- 弹窗 -->
    <p-modal title="预约调整" width="80%" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="visible = false">
      <p-form-model ref="dialogForm" :model="dialogForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" class="plg-grid-from" :rules="rules">
        <a-row>
          <a-col :span="12">
            <p-form-model-item label="预约地点" prop="branchName">
              <p-input v-model="dialogForm.branchName" disabled />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <p-form-model-item label="预约日期" prop="appointmentDate">
              <p-date-picker v-model="dialogForm.appointmentDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" style="width: 100%" />
            </p-form-model-item>
          </a-col>
          <a-col :span="12">
            <p-form-model-item label="预约时间" prop="appointmentTime">
              <p-select v-model="dialogForm.appointmentTime" :options="options.appointmentTimeEnums" allowClear />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <p-form-model-item label="预约司机" prop="driverName">
              <p-input v-model="dialogForm.driverName" />
            </p-form-model-item>
          </a-col>
          <a-col :span="12">
            <p-form-model-item label="预约电话" prop="driverPhoneNumber">
              <p-input v-model="dialogForm.driverPhoneNumber" />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <p-form-model-item label="车牌号" prop="vehiclePlateNumber">
              <p-input v-model="dialogForm.vehiclePlateNumber" />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row v-show="selectedRowKeys.length > 1">
          <a-col :span="12">
            <p-form-model-item label="运单数">
              <p-input :value="selectedRowKeys.length" disabled />
            </p-form-model-item>
          </a-col>
        </a-row>
      </p-form-model>
      <a-collapse defaultActiveKey="1" v-if="dialogForm.bookingViewByOneDetailDTOS.length">
        <a-collapse-panel key="1" :header="'运单数:' + dialogWaybillDataSource.length">
          <div style="text-align: right; padding-bottom: 12px">
            <a-space>
              <p-button type="primary" @click="onAdd">添加运单</p-button>
              <p-button type="danger" @click="onDel" :disabled="!dialogWaybillSelectedRowKeys.length">剔除运单</p-button>
            </a-space>
          </div>
          <t-table
            ref="dialogWaybillTable"
            dragle
            bordered
            row-key="shipbillId"
            :scroll="{ x: true, y: 300 }"
            :columns="dialogWaybill_columns"
            :data-source.sync="dialogWaybillDataSource"
            :remoteData="dialogWaybillListParams"
            :rowSelectType="2"
            :selectedRowKeys.sync="dialogWaybillSelectedRowKeys"
            :autoLoad="false"
            :pagination="false"
          >
          </t-table>
        </a-collapse-panel>
      </a-collapse>

      <p-search-modal v-bind="setQueryFormItmes.waybillAttr" @change="(...args) => onFormBlur('waybill', ...args)" v-show="false" :open="waybillDialog" />
    </p-modal>
  </div>
</template>

<script>
import { initDictionary, resultExtendedField } from '@/blocks/utils'
import { UPCLOUD_RDC_TMS_BUSINESS_SERVICE } from '@/config/serviceSettings.js'
import exportButton from '@/blocks/components/export-modal/modal.index.vue'
import * as $formItems from '@/blocks/components/searchModalConfig/index.js'

import { listRemoteUrl, waybillListRemoteUrl, goodsListRemoteUrl, packListRemoteUrl, Cancel, Review, view_one, update_batch, update_one, queryBranchTime } from './js/api'
import { setWaybillColumns, setGoodsColums, setPackColums } from '../js/tableConfig.js'
import { setMainColumns } from './js/tableConfig.js'
import { setQueryFormItmes, setDialogWaybillColumns } from './js/form.js'

export default {
  components: { exportButton },
  computed: {
    estimatedPickupTime: {
      get() {
        return [this.form.startDate, this.form.endDate]
      },
      set(value) {
        this.$set(this.form, 'startDate', value.length ? value[0] : '')
        this.$set(this.form, 'endDate', value.length ? value[1] : '')
      },
    },
    selectedRowKeysLength() {
      return this.selectedRowKeys.length
    },
  },
  data() {
    return {
      $formItems,
      UPCLOUD_RDC_TMS_BUSINESS_SERVICE,
      spinning: false,
      editType: '',

      branchInfo: {
        branchId: '',
        branchName: '',
      },
      form: {
        startDate: '',
        endDate: '',
      },
      options: {
        APPOINTMENT_TYPE: [],
        ORDER_BUSINESS_TYPE: [],
        appointmentTimeEnums: [],
        APPOINTMENT_STATUS: [],
      },

      rules: {
        branchName: [{ required: true, message: '仓库不能为空', trigger: 'change' }],
        appointmentDate: [{ required: true, message: '预约日期不能为空', trigger: 'change' }],
        appointmentTime: [{ required: true, message: '预约时间不能为空', trigger: 'change' }],
        driverName: [{ required: true, message: '预约司机不能为空', trigger: 'change' }],
        driverPhoneNumber: [{ required: true, message: '预约电话不能为空', trigger: 'change' }],
        vehiclePlateNumber: [{ required: true, message: '车牌号不能为空', trigger: 'change' }],
      },

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      listRemoteUrl,
      listParams: {},
      mainPages: { pageNum: 1, pageSize: 15 },
      buttonDisabled: true,
      tableExtendedField: [],
      mx_columns: setMainColumns(this, this.tableExtendedField),

      // 运单表格
      waybillDataSource: [],
      waybillListRemoteUrl,
      waybillListParams: {},
      waybillTableExtendedField: [],
      waybill_columns: setWaybillColumns(this, this.waybillTableExtendedField),

      // 商品表格
      goodsDataSource: [],
      goodsListRemoteUrl,
      goodsListParams: {},
      goods_columns: setGoodsColums(this),

      // 包裹表格
      packDataSource: [],
      packListRemoteUrl,
      packListParams: {},
      pack_columns: setPackColums(this),

      // 弹窗数据
      visible: false,
      confirmLoading: false,
      dialogForm: {
        branchId: '',
        branchName: '',
        appointmentIds: [],
        bookingViewByOneDetailDTOS: [],
      },

      setQueryFormItmes: setQueryFormItmes(this),
      waybillDialog: false,

      // 运单表格
      dialogWaybillDataSource: [],
      dialogWaybillSelectedRowKeys: [],
      dialogWaybillListParams: {},
      dialogWaybill_columns: setDialogWaybillColumns(this, this.waybillTableExtendedField),
    }
  },
  watch: {
    selectedRowKeysLength(val) {
      let selectList = []
      this.dataSource.forEach((item) => {
        if (this.selectedRowKeys.includes(item.appointmentId) && item.status < 20) {
          selectList.push(item)
        }
      })
      this.buttonDisabled = selectList.length !== this.selectedRowKeys.length
    },
  },
  mounted() {
    initDictionary([{ objectcode: 'APPOINTMENT_TYPE' }, { objectcode: 'ORDER_BUSINESS_TYPE' }, { objectcode: 'APPOINTMENT_STATUS' }]).then((res) => {
      this.options.APPOINTMENT_TYPE = res.APPOINTMENT_TYPE.map((item) => {
        item.value = +item.value
        return item
      })
      this.options.ORDER_BUSINESS_TYPE = res.ORDER_BUSINESS_TYPE.map((item) => {
        item.value = +item.value
        return item
      })
      this.options.APPOINTMENT_STATUS = res.APPOINTMENT_STATUS.map((item) => {
        item.value = +item.value
        return item
      })
    })
    // resultExtendedField({ extendedObjectCode: '6' }).then((res) => {
    //   if (res) {
    //     this.tableExtendedField = res.table
    //   }
    // })
    // resultExtendedField({ extendedObjectCode: '13' }).then((res) => {
    //   if (res) {
    //     this.waybillTableExtendedField = res.table
    //   }
    // })

    let warehouseList = this.$store.getters.userInfo.warehouseList
    if (warehouseList && warehouseList.length === 1) {
      this.branchInfo.branchId = warehouseList[0].warehouseId
      this.branchInfo.branchName = warehouseList[0].warehouseName
    }
  },
  methods: {
    // 查询
    onSearch() {
      this.waybillDataSource = []
      this.goodsDataSource = []
      this.packDataSource = []
      this.listParams = { ...this.form, branchId: this.branchInfo.branchId }
    },
    // 重置
    onReset() {
      this.form = {}
    },
    doneBefore(res) {
      if (res.data) {
        const { pageNum, pageSize } = res.data
        this.mainPages = { pageNum, pageSize }
      }
    },

    // 审核
    onAudit() {
      this.onBindConfirm(this.selectedRowKeys, Review, '审核')
    },
    toAudit(record) {
      this.onBindConfirm([record.appointmentId], Review, '审核')
    },
    // 取消
    onCancel() {
      this.onBindConfirm(this.selectedRowKeys, Cancel, '取消')
    },
    toCancel(record) {
      this.onBindConfirm([record.appointmentId], Cancel, '取消')
    },
    onBindConfirm(list, Method, txt) {
      let self = this
      this.$confirm({
        title: '是否' + txt + '？',
        onOk() {
          return new Promise((resolve, reject) => {
            self.spinning = true
            Method(list)
              .then((res) => {
                self.spinning = false
                if (res.success) {
                  self.$message.success(res.message)
                  self.onSearch()
                  resolve()
                } else {
                  self.$exception(res)
                  resolve()
                }
              })
              .finally(() => {
                self.spinning = false
              })
          })
        },
      })
    },

    // 批量调整
    onAdjust() {
      if (this.selectedRowKeys.length === 1) {
        this.toAdjust({ appointmentId: this.selectedRowKeys[0] })
      } else {
        this.dialogForm = {
          branchId: this.branchInfo.branchId,
          branchName: this.branchInfo.branchName,
          appointmentIds: [...this.selectedRowKeys],
          bookingViewByOneDetailDTOS: [],
        }
        this.visible = true
      }
    },
    // 单个调整
    toAdjust(record) {
      this.spinning = true
      view_one({ appointmentId: record.appointmentId })
        .then((res) => {
          if (res.success) {
            this.dialogForm = { ...res.data, branchId: this.branchInfo.branchId, branchName: this.branchInfo.branchName, appointmentId: record.appointmentId }
            this.dialogWaybillDataSource = [...this.dialogForm.bookingViewByOneDetailDTOS]
            this.visible = true
          } else {
            this.$exception(res)
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },

    masterClickRow(event, activeID, rowRecord) {
      this.waybillListParams = { appointmentId: rowRecord.appointmentId }
      this.goodsListParams = { appointmentId: rowRecord.appointmentId }
      this.packListParams = { appointmentId: rowRecord.appointmentId }
    },

    // 调整确认
    handleOk() {
      this.$refs.dialogForm.validate((valid) => {
        if (!valid) return
        let request = { ...this.dialogForm }
        if (this.dialogForm.appointmentIds > 1) {
          // 批量
          this.confirmLoading = true
          update_batch(request)
            .then((res) => {
              if (res.success) {
                this.visible = false
                this.$message.success(res.message)
                this.$refs.masterTable.reload()
              } else {
                this.$exception(res)
              }
            })
            .finally(() => {
              this.confirmLoading = false
            })
        } else {
          // 单个
          request.shipbillIds = this.dialogWaybillDataSource.map((item) => item.shipbillId)
          request.shipbillQuantity = request.shipbillIds.length
          this.confirmLoading = true
          update_one(request)
            .then((res) => {
              if (res.success) {
                this.visible = false
                this.$message.success(res.message)
                this.$refs.masterTable.reload()
              } else {
                this.$exception(res)
              }
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },

    onFormChange(name, ...args) {
      if (args[2].length) {
        this.branchInfo.branchId = args[2][0].id
        this.branchInfo.branchName = args[2][0].name
        this.queryBranchTime()
      } else {
        this.branchInfo.branchId = ''
        this.branchInfo.branchName = ''
      }

      this.dataSource = []
      this.waybillDataSource = []
      this.goodsDataSource = []
      this.packDataSource = []
    },

    // 获取仓库绑定的预约时间
    queryBranchTime() {
      queryBranchTime({ branchId: this.branchInfo.branchId }).then((res) => {
        this.options.appointmentTimeEnums = [...res.data]
      })
    },

    onAdd() {
      this.waybillDialog = false
      setTimeout(() => {
        this.waybillDialog = true
      }, 100)
    },
    onDel() {
      let newList = []
      this.dialogWaybillDataSource.forEach((item) => {
        if (!this.dialogWaybillSelectedRowKeys.includes(item.shipbillId)) {
          newList.push(item)
        }
      })
      this.dialogWaybillDataSource = [...newList]
    },
    onFormBlur(name, ...args) {
      if (name === 'waybill') {
        args[2].forEach((item) => {
          let index = this.dialogWaybillDataSource.findIndex((item2) => item2.id === item.id)
          if (index === -1) {
            this.dialogWaybillDataSource.push(item)
          }
        })
      }
    },
  },
}
</script>

<style lang="less">
.booking {
  .ant-card-extra {
    width: 50%;
  }
}
</style>