/*
 *@description：待自提
 *@author: hudw
 *@date: 2022-06-16 11:35:37
*/
<template>
  <div class="pages">
    <updateFormModal ref="updateFormModal" rowKey="bzid" :visible.sync="visible" :view="2" :count="8" @ok="handle_ok" :title="card_title" :currentData="currentData" :formItems="updateFormItems" />
    <orderView
    :formExtendedField="formExtendedField"
      v-show="detailsState === 1"
      :parcelTable="true"
      :st="1"
      :exportUrls="exportUrls"
      :goods="goods"
      :parcel="parcel"
      :record="mainCurrent"
      :mainId="mainId"
      :options="options"
      :formName="'main'"
      @back="onBack"
    />
    <!-- <spliceShipbill :visible="detailsState == 10" :goodsUrl="goodsTableUrl" :record="mainCurrent" @back="onBack" /> -->

    <split v-if="detailsState == 10" :selectedRow="mainCurrent" @back="onBack"></split>

    <!-- 策略拆分弹出框 -->
    <p-modal
      title="策略拆分"
      width="720px"
      :visible="splVisible"
      :confirm-loading="confirmLoading"
      @cancel="
        () => {
          splVisible = false
          confirmLoading = false
        }
      "
      @ok="handleOk"
    >
      <div v-for="(item, index) in strategySplitMatchingDTOS" :key="index">
        <p-form-model
          :model="item"
          layout="vertical"
          :rules="{
            strategy: [{ required: true, message: '拆分策略不能为空', trigger: 'change' }],
          }"
        >
          <p-form-model-item :label="'运单号 ' + item.shipbillId" prop="strategy">
            <p-radio-group v-model="item.strategy" :options="item.strategyEnums" />
          </p-form-model-item>
        </p-form-model>
      </div>
    </p-modal>

    <div class="pages" v-show="detailsState === 0">
      <searchBar ref="searchBar" :fromItems="queryFromItems" :options="options" @submit="searchSubmit" />
      <mainTable
        ref="mainTable"
        title="运单信息"
        rowKey="_row_count"
        :mode="0"
        :url="mainTableInfoUrl"
        :exportUrls="exportUrls"
        :tableColumnsList="tableColumnsList"
        :options="options"
        :activeID="mainId"
        :tableExtendedField="tableExtendedField"
        @clickRow="handleRowClick"
        :operation="{ width: 240 }"
        @view="handleView"
        @selectChange="selectChange"
        @print="handPrint"
      >
        <template #extra>
          <p-button type="primary" :disabled="mainsSelectedRowKeys.length === 0" @click.stop="onPolicySplit(mainsSelectedRowKeys)">策略拆分</p-button>
          <p-button type="primary" :disabled="mainsSelectedRowKeys.length === 0" @click.stop="handelFeedback('自提车辆登记', mainsSelectedRowKeys)">自提车辆登记</p-button>
          <p-button type="primary" :disabled="mainsSelectedRowKeys.length === 0" @click.stop="handelFeedback('自提确认', mainsSelectedRowKeys)">自提确认</p-button>
        </template>

        <a-space slot="operation" :size="10" slot-scope="props">
          <a href="javascript:;"
          v-action:shipbillSplit
          :disabled="~~props.record.status === 180" @click.stop="handelSpliceShipbill(props.record)">运单拆分</a>
          <a href="javascript:;"
          v-action:selfStoreCarCheck
          :disabled="~~props.record.status === 180" @click.stop="handelFeedback('自提车辆登记', [props.record])">自提车辆登记</a>
          <a href="javascript:;"
           v-action:selfStoreConfirm
          :disabled="~~props.record.status === 30" @click.stop="handelFeedback('自提确认', [props.record])">自提确认</a>
        </a-space>
      </mainTable>
      <a-row :gutter="10">
        <a-col :span="12">
          <p-card :bordered="false" title="商品信息" style="min-height: 300px">
            <goodsTable ref="goodsTable" :url="goodsTableUrl" :options="options" :activeID="mainId" :tableExtendedField="tableExtendedField" />
          </p-card>
        </a-col>
        <a-col :span="12">
          <p-card :bordered="false" title="包裹信息" style="min-height: 300px">
            <parcelTable ref="parcelTable" :url="packageTableUrl" :options="options" :activeID="mainId" :tableExtendedField="tableExtendedField" />
          </p-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>
<script>
import useMixin from '../$common/mixins/useMixin.js'
import dictionary from '../$common/mixins/dictionary.js' //@字典
import { queryConfirm, mainTableInfoUrl, goodsTableUrl, packageTableUrl, confirmSubmit, printUrl, exportUrls, smart_split, smart_split_strategy } from './api.js'
import { setUpdateForm, setVehicleRegisterForm } from './config.js'
import { setMainColumns } from './tableConfig.js'
import queryFormConfig from './queryFormConfig'

export default {
  mixins: [useMixin, dictionary],
  components: {
    split: () => import(/* webpackChunkName: "$toPickUp-split" */ './split/split.vue'), //@拆分运单组件
  },
  data() {
    const goods = {
      url: goodsTableUrl,
    }
    const parcel = {
      url: packageTableUrl,
    }
    return {
      queryFromItems:queryFormConfig(this),
      tableColumnsList: [setMainColumns],
      currentData: null,
      goods,
      exportUrls,
      parcel,
      printUrl,
      goodsTableUrl,
      packageTableUrl,
      card_title: '',
      mainTableInfoUrl,
      visible: false,
      updateFormItems: null,
      confirmLoading: false,
      detailsState: 0 /**0=不显示, 1=新建，2=修改 ，3=查看 ，4=复制 10=拆分运单 */,
      // 策略拆分

      splVisible: false,
      strategySplitMatchingDTOS: [],
    }
  },
  mounted() {},
  methods: {
    selectChange(selectKey, selectData) {
      this.selectedRowKeys=selectKey

      this.mainsSelectedRowKeys = selectData
    },
    handelSpliceShipbill(record) {
      this.mainCurrent = null
      this.$nextTick(() => {
        this.detailsState = 10
        this.mainCurrent = record
      })
    },

    handelFeedback(title, arr) {
      let _this = this
      let record = arr.map((item) => {
        let _id = item.shipbillId
        if (item.shipbillIds) {
          _id = item.shipbillIds
        }
        return _id
      })
      record = record.join(',')
      this.currentData = { ids: record, bzid: record }
      this.card_title = title

      if (title == '自提车辆登记') {
        this.updateFormItems = setVehicleRegisterForm(this, title)
      } else if (title == '自提确认') {
        this.$refs.updateFormModal.confirmLoading = true

        queryConfirm(this, { shipbillIds: record.split(',') }).then((response) => {
          if (response.success) {
            // _this.currentData = { ..._this.currentData, ...response.data }
            _this.currentData = Object.assign({}, _this.currentData, response.data)
            let form = _this.$refs?.updateFormModal?.form()
            if (form) {
              form.setFieldsValue(_this.currentData)
            }
          } else {
            _this.visible = false
            _this.$exception(response)
          }
          _this.$refs.updateFormModal.confirmLoading = false
        })
        this.updateFormItems = setUpdateForm(this, title)
      } else {
        return
      }
      this.$nextTick(() => {
        this.visible = true
      })
    },

    handle_ok(submit, close) {
      let _this = this
      return submit().then((values) => {
        if (values === null) return close()

        _this.$refs.updateFormModal.confirmLoading = true
        values.shipbillIds = values.ids.split(',')
        values.picUrl = values.picture
        delete values.picture
        return confirmSubmit(this, values, close).finally(() => {
          _this.$refs.updateFormModal.confirmLoading = false
        })
      })
    },

    handleRowClick(event, key, data) {
      event.stopPropagation()
      this.mainId = key
      this.clearChildrenTableAll()
      if (key) {
        this.mainCurrent = data
        const { goodsTable, parcelTable } = this.$refs
        goodsTable.reload({ data: { shipbillId: data.shipbillId } })
        parcelTable.reload({ data: { shipbillId: data.shipbillId } })
      }
    },

    onPolicySplit(mainsSelectedRowKeys) {
      let record = mainsSelectedRowKeys.map((item) => {
        let _id = item.shipbillId
        if (item.shipbillIds) {
          _id = item.shipbillIds
        }
        return _id
      })
      let confirmLoading = false
      let _this = this
      this.$confirm({
        title: '是否策略拆分?',
        confirmLoading,
        onOk(clear) {
          confirmLoading = true
          return smart_split({ shipbillIds: record })
            .then((res) => {
              if (res.success) {
                console.log(res)
                if (res.data.length) {
                  _this.strategySplitMatchingDTOS = res.data.map((item) => {
                    item.strategy = item.strategySplitMatchingDTOS[0].id
                    item.strategyEnums = item.strategySplitMatchingDTOS.map((item2) => {
                      return {
                        value: item2.id,
                        label: item2.name,
                      }
                    })
                    console.log(item)
                    return item
                  })
                  _this.splVisible = true
                } else {
                  _this.$message.success(res.message)
                  _this.clearChildrenTableAll()
                  _this.$refs.mainTable.reload()
                }
              } else {
                _this.$exception(res)
              }
            })
            .finally(() => {
              clear()
            })
        },
      })
    },

    handleOk() {
      let list = this.strategySplitMatchingDTOS.map((item) => {
        let index = item.strategySplitMatchingDTOS.findIndex((item2) => item2.id === item.strategy)
        return { ...item.strategySplitMatchingDTOS[index], shipbillId: item.shipbillId, strategyId: item.strategySplitMatchingDTOS[index].id }
      })

      this.confirmLoading = true
      smart_split_strategy(list)
        .then((res) => {
          if (res.success) {
            this.splVisible = false
            this.$message.success(res.message)
            this.clearChildrenTableAll()
            this.$refs.mainTable.reload()
          } else {
            this.$exception(res)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
  },
}
</script>
<style lang='less'>
</style>


