/*
 *@description:归还容器弹出框
 *@author: hudw
 *@date: 2022-03-14 10:40:55
*/

<template>
  <a-modal class="model-table" destroyOnClose v-model="sVisible" v-bind="modalConfig" :title="mode" :confirmLoading="confirmLoading" @ok="handleOk">
    <!-- :labelCol="{ span: 9 }" :wrapperCol="{ span: 14 }" -->
    <p-grid-form ref="girdAbnormal" v-if="mode == '异常处理'" :items="fromItems" />
    <operationLog v-if="mode == '日志' && record" :editId="record.containerId" />
    <template v-if="['归还容器', '在途容器-归还容器-修改', '在途容器-归还容器-签收'].includes(mode)">
      <p-grid-form ref="searchBar" :span="6" @submit="searchSubmit">
        <p-grid-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }" :span="12" name="containerCode" label="容器编码" type="input" />
        <a-space>
          <p-button icon="search" type="primary" htmlType="submit">查询</p-button>
          <p-button icon="redo" @clickSync="(event) => $refs.searchBar.form.resetFields()">重置</p-button>
        </a-space>
      </p-grid-form>
      <!-- consigneeName -->
      <div class="pull-warpped horizontal c3" style="width: 100%">
        <label>门店:{{ record && mode == '归还容器' ? record.consigneeName : recordList[0].shipperName }}</label>
        <a-space size="middle">
          <a-statistic title="容器总数" :value="countList.containersNumbers" />
          <a-statistic title="托盘" :value="countList.palletsNumbers" />
          <a-statistic title="周转箱" :value="countList.totesNumbers" />
        </a-space>
      </div>

      <p-grid-form ref="gird" v-if="mode!='在途容器-归还容器-签收'" :span="6"  :labelCol="{ span: 7}" :wrapperCol="{ span: 17 }" :items="fromItems" />
      <!-- layout="inline" -->
      <p-grid-form ref="girdEdit" :labelCol="{ span: 7}" :wrapperCol="{ span: 17 }"  v-if="['在途容器-归还容器-修改', '在途容器-归还容器-签收'].includes(mode)" :span="6">
        <p-grid-form-item name="containerBillNo" label="容器归还单号" type="txt" />
        <p-grid-form-item name="statusName" label="当前状态" type="txt" />
        <p-grid-form-item name="containerBillDate" label="下单时间" type="txt" />
        <p-grid-form-item name="shipperName"  label="发货方" type="txt" />
        <p-grid-form-item name="driverName" v-if="mode=='在途容器-归还容器-签收'"  label="司机姓名" type="txt" />
        <p-grid-form-item name="driverPhoneNumber" v-if="mode=='在途容器-归还容器-签收'"  label="司机电话" type="txt" />
        <p-grid-form-item name="vehiclePlateNumber" v-if="mode=='在途容器-归还容器-签收'"  label="运输车辆" type="txt" />
        <p-grid-form-item name="consigneeName" label="收货方" type="txt" />
      </p-grid-form>
      <p-card
        :bordered="true"
        title="容器明细"
        :bodyStyle="{
          height: '376px',
        }"
      >
        <a-space slot="extra">
          <p-button v-if="mode == '在途容器-归还容器-签收'" type="primary" :disabled="!selectedRowKeys.length" @clickSync="handleState(selectedRowKeys)">缺货</p-button>
          <p-button v-if="mode == '在途容器-归还容器-签收'" type="primary" @clickSync="addTableItem">多货登记</p-button>
          <p-button v-else :disabled="!selectedRowKeys.length" @click.stop="remove(selectedRowKeys)">删除</p-button>
        </a-space>
        <p-table-edit-pro
          v-if="mode == '在途容器-归还容器-签收'"
          ref="table"
          rowKey="_row_count"
          bordered
          :selectedRowKeys.sync="selectedRowKeys"
          :autoLoad="false"
          :remoteUrl="{
            url: containerDetailsUrl,
            method: 'post',
          }"
          :pagination="false"
          :remoteBefore="remoteBefore"
          :columns="columns"
          :dataSource.sync="dataSource"
          :getCheckboxProps="getCheckboxProps"
        >
        </p-table-edit-pro>
        <p-table
          v-else
          ref="table"
          bordered
          :selectedRowKeys.sync="selectedRowKeys"
          :autoLoad="false"
          hasRowSelectCheck
          :remoteUrl="{
            url: containerDetailsUrl,
            method: 'post',
          }"
          :remoteBefore="remoteBefore"
          :columns="columns"
          :pagination="false"
          :dataSource.sync="dataSource"
        >
          <template slot="operation" slot-scope="value, props">
            <a href="javascript:;" @click.stop="remove([props.id])">删除</a>
          </template>
        </p-table>
      </p-card>
    </template>
  </a-modal>
</template>
<script>
import mainTable from '../mainTable/index.mainTable.vue';
import operationLog from './operationLog';
import { setContinerColumns } from '../mainTable/tableConfig';
import { setFromItems, setContinerEditColumns } from './setConfig';

import { modifyContinent, receiptedContinent, detailsTableUrl, containerDetailsUrl, submitContientAbnormal, saveContinent } from '../api';
function infoCount() {
  return {
    containersNumbers: 0,
    palletsNumbers: 0,
    totesNumbers: 0,
  };
}

export default {
  name: 'inMoneyModal',
  components: { mainTable, operationLog },
  props: {
    options: {
      type: Object,
      default: () => {},
    },
    record: {
      type: null,
    },
    recordList: {
      type: null,
    },
    /**0=不显示, 1=新建，2=修改 ，3=查看 */
    view: 0,
    title: '',
    visible: false,
    targetKeys: [],
    mode: {
      type: null,
    },
  },

  computed: {
    modalConfig() {
      const { title } = this;
      // okButtonProps: { props: { disabled: this.details.length === 0 } }
      let okText = { 归还容器: '归还容器', '在途容器-归还容器-修改': '保存修改', '在途容器-归还容器-签收': '确认签收' };
      return { title, width: 600, destroyOnClose: true, footer: this.mode == '日志' ? null : undefined, okText: okText[this.mode] };
    },
  },
  data() {
    return {
      countList: infoCount(),

      // sysParams,
      containerDetailsUrl,
      selectedRowKeys: [],
      dataSource: [],

      confirmLoading: false,
      details: [],
      sVisible: this.visible,
      scolumns: [],
      shipperData: [],
      fromItems: [],
    };
  },

  watch: {
    visible(value) {
      this.details = [];
      this.dataSource = [];
      this.shipperData = [];
      this.sVisible = value;
      if (value) {
        switch (this.mode) {
          case '异常处理':
            this.modalConfig.width = 480;
            this.fromItems = [
              {
                subName: ['id'],
                label: '异常状态',
                type: 'select',
                required: true,
                name: 'abnormalStatus',
                options: this.options.CONTAINER_ABNORMAL_STATUS.filter(item =>[0,3].includes(~~item.value)),
              },
              {
                label: '异常备注',
                type: 'textarea',
                name: 'abnormalMemo',
              },
            ];
            this.$nextTick(() => {
              const { id } = this.record;
              this.$refs.girdAbnormal.form.setFieldsValue({ id });
            });

          case '日志':
            return;
          case '归还容器':
          case '在途容器-归还容器-修改':
          case '在途容器-归还容器-签收':
            if (['在途容器-归还容器-修改', '在途容器-归还容器-签收'].includes(this.mode) && this.record) {
              this.$nextTick(() => {
                this.$refs?.girdEdit?.form.setFieldsValue(this.record);
                this.$refs?.gird?.form.setFieldsValue(this.record);
              });
            }
            if (this.mode == '在途容器-归还容器-签收') {
              this.columns = setContinerEditColumns(this);
            } else {
              this.columns = setContinerColumns(this);
            }
            this.modalConfig.width = '70%';
            this.fromItems = setFromItems(this);
            if (this.recordList.length > 0) {

              setTimeout(() => {
                this.$refs?.gird?.form?.setFieldsValue(this.recordList[0]);
                this.reload();
              }, 100);
            }
            break;
          default:
            break;
        }
      }
    },

    sVisible(value) {
      this.confirmLoading = false;
      if (value && this.view > 0) {
      } else {
      }
      this.$emit('update:visible', value);
    },
  },
  mounted() {},
  methods: {
    // handelRemove(record) {
    //   this.$refs.table.removeRow(record._row_count);
    // },
    handleState(kes) {
      for (let i = 0; i < this.dataSource.length; i++) {
        let record = this.dataSource[i];
        if (kes.includes(record._row_count)) {
          record.abnormalStatus = 1;
          record.abnormalStatusName = '缺货';
        }
      }
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.id === null,
        },
      };
    },
    addTableItem() {
      this.$refs.table.createRow(
        {
          containerTypeName: '',
          containerType: null,
          containerCode: '',
          containerId: null,
          abnormalStatus: 2,
          id: null,
        },
        false
      );
    },
    reload() {
      this.countList = infoCount();
      this.$refs.table.reload().then((res) => {
        if (res?.success) {
          this.countList.containersNumbers = res.data.length;
          res.data.forEach((item, inde) => {
            if (item.containerType === 1) {
              this.countList.palletsNumbers += 1;
            } else if (item.containerType === 2) {
              this.countList.totesNumbers += 1;
            }
          }, this);
        }
      });
    },
    searchSubmit(event) {
      event.preventDefault();
      this.reload();
      //   let value=this.$refs.searchBar.form.getFieldsValue()
    },
    remoteBefore(vNode, remoteUrl) {
      let value = this.$refs.searchBar.form.getFieldsValue();
      let shipperName = this.recordList[0].shipperName;
      if (['在途容器-归还容器-修改', '在途容器-归还容器-签收'].includes(this.mode)) {
        remoteUrl.url = detailsTableUrl;
        const { containerBillNo } = this.record;
        remoteUrl.data = { ...value, ...remoteUrl.data };
        remoteUrl.data.containerBillNo = containerBillNo;
        remoteUrl.data.pageNum = 1;
        remoteUrl.data.pageSize = 9999;
        this.$refs.gird.form.setFieldsValue({ shipperName, containerBillNo });
      } else {
        let containerBillNos = this.recordList.map((item) => {
          return item.containerBillNos;
        });
        remoteUrl.data = { ...value, ...remoteUrl.data };
        containerBillNos = containerBillNos.flat();
        containerBillNos = containerBillNos.join(',');
        remoteUrl.data.containerBillNos = containerBillNos;
        remoteUrl.data.pageNum = 1;
        remoteUrl.data.pageSize = 9999;
        this.$refs.gird.form.setFieldsValue({ shipperName, containerBillNos });
      }

      //if (!containerBillNos) return false;
    },

    remove(arr) {
      this.dataSource = this.dataSource.filter((item) => !arr.includes(item.id));
      this.countList = infoCount();
      this.countList.containersNumbers = this.dataSource.length;
      this.dataSource.forEach((item, inde) => {
        if (item.containerType === 1) {
          this.countList.palletsNumbers += 1;
        } else if (item.containerType === 2) {
          this.countList.totesNumbers += 1;
        }
      }, this);
    },

    handleOk() {
      let _this = this;

      switch (this.mode) {
        case '异常处理':
          return this.$refs.girdAbnormal.form.validateFields((errors, values) => {
            if (errors) return;
            this.confirmLoading = true;
            this.$emit('ok', submitContientAbnormal(this, values));
          });

        case '日志':
          return;
        case '归还容器':
          return this.$refs.gird.form.validateFields((errors, values) => {
            if (errors) return;
            values.details = this.dataSource;
            this.confirmLoading = true;
            this.$emit('ok', saveContinent(this, values));
          });
        case '在途容器-归还容器-修改':
        case '在途容器-归还容器-签收':
          return this.$refs.girdEdit.form.validateFields((errors, values) => {
            if (errors) return;
            values.details = this.dataSource;
            this.confirmLoading = true;
            if (this.mode == '在途容器-归还容器-修改') {
              this.$emit('ok', modifyContinent(this, values));
            }
            if (this.mode == '在途容器-归还容器-签收') {
              this.$emit('ok', receiptedContinent(this, values));
            }
          });
        default:
          break;
      }
    },
  },
};
</script>

<style  lang="less" scoped>
</style>


