/*
 *@description:明细
 *@author: hudw
 *@date: 2022-03-14 15:14:53
*/
<template>
  <div>
    <updateFormModal ref="updateFormModal" v-if="activeKey === '3'" :visible.sync="visible" :btnSave="btnSave" :view="card_view" @ok="handle_ok" :title="card_title" :currentData="card_data" />
    <a-tabs v-model="activeKey" :default-active-key="'1'" :animated="false" type="card">
      <template slot="tabBarExtraContent">
        <p-button v-if="['1', '4', '5'].includes(activeKey) && !bind && st !== 3" :disabled="rmBtnDisabled" @clickSync="removeItem(activeKey)" type="danger">删除</p-button>
        <a-space v-else-if="activeKey === '3' && st !== 3">
          <p-button @clickSync="add_card" :disabled="!currentMainRow && !btnSave" type="primary" icon="plus">新增</p-button>
          <p-button @clickSync="isEnable_item(1)" :disabled="selectedRowKeys_3.length === 0" type="primary">启用</p-button>
          <p-button @clickSync="isEnable_item(0)" :disabled="selectedRowKeys_3.length === 0" type="danger">停用</p-button>
          <p-button @click="delete_card(null)" :disabled="selectedRowKeys_3.length === 0" type="danger">删除</p-button>
        </a-space>
      </template>

      <a-tab-pane :key="'1'" :tab="bind ? '绑定司机' : '已绑司机'">
        <transfer-table v-if="bind && activeKey == '1'" :columns="bindCarColumns" :transferData="transferData" :targetKeys="targetKeys" :loading="confirmLoading" @change="handleDataAutoChange" />
        <t-table
          :customScrollbar="true"
          v-if="!bind && activeKey == '1'"
          rowKey="_row_count"
          :dataSource.sync="dataSource_1"
          @selectChange="(selectKey, selectData) => (selectedRowKeys_1 = selectData)"
          :scroll="{ x: true }"
          :vScrollY="{ enabled: true, rows: 8 }"
          :id="$route.meta.menuId + '_tabTable_1'"
          ref="table_1"
          :autoLoad="false"
          bordered
          :columns="carManColumns"
          :remoteUrl="{ url: getBindCarUrl, method: 'post' ,data:{vehicleId:currentMainRow&&currentMainRow.id}}"
          dragle
          :rowSelectType="2"
        >
          <template v-if="st !== 3" slot="operation" slot-scope="text, record">
            <a href="javascript:;" @click.stop="removeVehicle(record)">删除</a>
          </template>
        </t-table>
      </a-tab-pane>
      <a-tab-pane :key="'4'" tab="绑定设备">
        <transfer-table
          v-if="bind && activeKey === '4'"
          :columns="Equipment.t_columns"
          @change="EquipmentChange"
          :transferData="Equipment.transferData"
          :targetKeys="Equipment.targetKeys"
          :loading="confirmLoading"
          :talbeTitle="['待绑设备', '已绑设备']"
        />
        <t-table
          v-if="!bind && activeKey === '4'"
          :customScrollbar="true"
          rowKey="id"
          :dataSource.sync="dataSource_4"
          @selectChange="(selectKey, selectData) => (selectedRowKeys_4 = selectKey)"
          :scroll="{ x: true }"
          :vScrollY="{ enabled: true, rows: 8 }"
          :id="$route.meta.menuId + '_tabTable_4'"
          ref="table_4"
          :autoLoad="false"
          bordered
          :columns="Equipment.columns"
          :remoteUrl="{ url: Equipment.url, method: 'post',data:{vehicleId:currentMainRow&&currentMainRow.id} }"
          dragle
          :rowSelectType="2"
        >
          <template v-if="st !== 3" slot="operation" slot-scope="text, record">
            <a href="javascript:;" @click.stop="removeDevice(record)">删除</a>
          </template>
        </t-table>
      </a-tab-pane>
      <a-tab-pane :key="'5'" tab="绑定容器">
        <transfer-table
          v-if="bind && activeKey === '5'"
          :columns="container.t_columns"
          @change="(targetKeys, direction, moveKeys) => {
              container.targetKeys = targetKeys;
            }
          "
          :transferData="container.transferData"
          :targetKeys="container.targetKeys"
          :loading="confirmLoading"
          :talbeTitle="['待绑容器', '已绑容器']"
        />
        <t-table
          v-if="!bind && activeKey == '5'"
          :customScrollbar="true"
          rowKey="id"
          :dataSource.sync="dataSource_5"
          @selectChange="(selectKey, selectData) => (selectedRowKeys_5 = selectKey)"
          :vScrollY="{ enabled: true, rows: 8 }"
          :scroll="{ x: true }"
          :id="$route.meta.menuId + '_tabTable_5'"
          ref="table_5"
          :autoLoad="false"
          bordered
          :columns="container.columns"
          :remoteUrl="{ url: container.url, method: 'post',data:{vehicleId:currentMainRow&&currentMainRow.id}  }"
          dragle
          :rowSelectType="2"
        >
          <template v-if="st !== 3" slot="operation" slot-scope="text, record">
            <a href="javascript:;" @click.stop="removeContainer(record)">删除</a>
          </template>
        </t-table>
      </a-tab-pane>
      <a-tab-pane :key="'2'" tab="常跑线路">
        <t-table
          v-if="activeKey == '2'"
          :customScrollbar="true"
          :scroll="{ x: true }"
          :id="$route.name + '_tabTable_2'"
          rowKey="_row_count"
          ref="table_2"
          :autoLoad="false"
          :dataSource.sync="dataSource_2"
          :vScrollY="{ enabled: true, rows: 8 }"
          bordered
          :columns="carLinkColumns"
          :remoteUrl="{ url: getLinkUrl, method: 'post' }"
          dragle
          :rowSelectType="0"
        ></t-table>
      </a-tab-pane>
      <a-tab-pane :key="'3'" tab="证件资料">
        <t-table
          v-if="activeKey == '3'"
          :customScrollbar="true"
          :id="$route.name + '_tabTable_3'"
          :autoLoad="false"
          @selectChange="(selectKey, selectData) => (selectedRowKeys_3 = selectKey)"
          :scroll="{ x: true }"
          :vScrollY="{ enabled: true, rows: 8 }"
          ref="table_3"
          :dataSource.sync="dataSource_3"
          bordered
          :columns="certificateColumns"
          :remoteUrl="{ url: getCertificateUrl, method: 'post',data:{vehicleId:currentMainRow&&currentMainRow.id}  }"
          dragle
          :rowSelectType="2"
        >
          <template slot="operation" slot-scope="text, record">
            <a href="javascript:;" @click="show_info_item(record)">查看</a>
            <a-divider type="vertical" v-if="st !== 3" />
            <a href="javascript:;" v-if="st !== 3" @click="update_item(record)" :disabled="!record.status">修改</a>
            <a-divider v-if="st !== 3" type="vertical" />
            <p-switch v-if="st !== 3" :replaceFields="{ true: 10, false: 0 }" @click="toggle_item(record)" :checked="record.status" size="small"></p-switch>
            <a-divider v-if="st !== 3" type="vertical" />
            <a v-if="st !== 3" href="javascript:;" @click.stop="delete_card(record)">删除</a>
          </template>
        </t-table>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script>
import { setContainerCol, setContainerPopCol, setEquipmentCol, setEquipmentPopCol, bindCarColumns, carManColumns, carLinkColumns, certificateColumns } from './setConfig.js';
import {
  paper_container_url,
  removeDevice,
  removeVehicle,
  paperIsEnable,
  savePaper,
  getBindAll,
  getBindCarUrl,
  getLinkUrl,
  getCertificateUrl,
  removeCard,
  paper_device_url,
  getPopDevice,
  getPopContainer,
  removeContainer,
} from '../../js/api';

import transferTable from '../transfer-modal.vue';
import updateFormModal from '@/blocks/components/papersUpdateModal/index.updateFormModal.vue';
export default {
  components: { updateFormModal, transferTable },
  props: {
    clearAll: {
      type: Boolean,
      default: false,
    },
    options: {
      type: Object,
      default: () => {},
    },
    bind: {
      type: Boolean,
      default: false,
    },
    tabActive: {
      type: String,
      default: '1',
    },
    btnSave: {
      //true:缓存数据跟主表一起保存，false:直接调接口保存提交
      type: Boolean,
      default: false, //默认直接调接口保存提交
    },
    st: {
      /**0=不显示, 1=新建，2=修改 ，3=查看 */
      type: Number,
      default: 0,
    },
    currentMainRow: {
      type: Object,
      default: () => null,
    },
  },
  data() {
    return {
      Equipment: {
        url: paper_device_url,
        columns: setEquipmentCol(this),
        t_columns: setEquipmentPopCol(this),
        transferData: null,
        targetKeys: [],
      },
      container: {
        url: paper_container_url,
        columns: setContainerCol(this),
        t_columns: setContainerPopCol(this),
        transferData: null,
        targetKeys: [],
      },
      confirmLoading: false,
      activeKey: this.tabActive,
      getBindCarUrl,
      getLinkUrl,
      getCertificateUrl,
      bindCarColumns: bindCarColumns(this), //绑定
      carManColumns: carManColumns(this), //已绑
      carLinkColumns: carLinkColumns(this),
      certificateColumns: certificateColumns(this),
      transferData: null, //绑定司机数据
      targetKeys: [],
      card_show: false,
      visible: false,
      card_title: '',
      card_view: 0,
      card_data: null,
      dataSource_1: [],
      dataSource_2: [],
      dataSource_3: [],
      dataSource_4: [],
      dataSource_5: [],
      selectedRowKeys_1: [],
      selectedRowKeys_3: [],
      selectedRowKeys_4: [],
      selectedRowKeys_5: [],
    };
  },
  watch: {
    clearAll(is) {
      if (is) {
        this.dataSource_1 = [];
        this.dataSource_2 = [];
        this.dataSource_3 = [];
        this.dataSource_4 = [];
        this.dataSource_5 = [];
      }
    },

    dataSource_1(v) {
      this.targetKeys = v.map((item) => {
        return item.driverId;
      });
    },
    dataSource_4(v) {
      this.Equipment.targetKeys = v.map((item) => {
        return item.deviceId;
      });
    },
    dataSource_5(v) {
      this.container.targetKeys = v.map((item) => {
        return item.id;
      });
    },
    st: {
      handler(value) {
      if (value === 0) {
        this.Equipment.transferData =null;
        this.transferData = null;
         this.container.transferData = null
        this.card_view = value;
        this.updateActiveTab(this.activeKey, this.currentMainRow);
      } else if (value === 1) {
        this.updateActiveTab(this.activeKey, null);
        this.dataSource_1 = [];
        this.dataSource_2 = [];
        this.dataSource_3 = [];
        this.dataSource_4 = [];
        this.dataSource_5 = [];
       }
      },
      immediate: true,
    },
    currentMainRow(record) {
      if (record) {
        this.updateActiveTab(this.activeKey, record);
      }
    },
    activeKey: {
      handler(tabKey) {
        if (this.currentMainRow) {
          this.updateActiveTab(tabKey, this.currentMainRow);
        }
      },
      immediate: true,
    },
  },
  computed: {
    rmBtnDisabled() {
      return this['selectedRowKeys_' + this.activeKey]?.length === 0 ?? true;
    },
    refTable() {
      return this.$refs['table_' + this.activeKey];
    },
  },
  methods: {
    EquipmentChange(targetKeys, direction, moveKeys) {
              this.Equipment.targetKeys = targetKeys;
    },
    removeItem(activeKey) {
      if (activeKey === '1') {
        return this.removeVehicle(null);
      } else if (activeKey === '4') {
        return this.removeDevice(null);
      } else if (activeKey === '5') {
        return this.removeContainer(null);
      }
    },
    delete_card(record) {
      let data = [];
      let { id } = this.currentMainRow || {};
      if (record === null) {
        this.selectedRowKeys_3.forEach((key) => {
          data.push({ vehicleId: id, paperId: key });
        });
      } else {
        data = [{ vehicleId: id, paperId: record.id }];
      }

      removeCard(this, data, id);
    },

    removeVehicle(record) {
      const { lineId, id } = this.currentMainRow;
      let arr = [];
      if (!record) {
        arr = this.selectedRowKeys_1.map((record) => {
          return { lineid: record.lineId };
        });
      } else {
        arr = [{ lineid: record.lineId }];
      }
      return removeVehicle(this, arr, id);
    },
    removeDevice(record) {
      const { id } = this.currentMainRow;
      let arr = [];
      if (!record) {
        this.dataSource_4.forEach((item) => {
          if (this.selectedRowKeys_4.indexOf(item.id) > -1) {
            arr.push({ id: item.id });
          }
        }, this);
      } else {
        arr = [{ id: record.id }];
      }
      return removeDevice(this, arr, id);
    },
    removeContainer(record) {
      const { id } = this.currentMainRow;
      let arr = [];
      if (!record) {
        this.dataSource_5.forEach((item) => {
          if (this.selectedRowKeys_5.indexOf(item.id) > -1) {
            arr.push(item.linkId);
          }
        }, this);
      } else {
        arr = [record.linkId];
      }
      return removeContainer(this, arr, id);
    },
    updateActiveTab(tabKey, record) {
      if (tabKey === '1' && this.bind) {
        if (this.transferData == null) {
          this.transferData = [];
          //获取所有司机数据
          getBindAll(this, { pageSize: 9999, pageNum: 1 }).then((res) => {
            if (res.success) {
              this.transferData = res.data.list.map((item) => {
                return {
                  key: item.id,
                  title: item.name,
                  description: item.phoneNumber,
                  driverId: item.id,
                  driverName: item.name,
                  driverCode: item.code,
                  ...item,
                };
              });
            }
          });
          this.dataSource_1=[]
         this.axios({ url: getBindCarUrl, method: 'post', data: { vehicleId: record.id, pageSize: 9999, pageNum: 1 } })
          .then((response) => {
            if (response.success) {
              this.dataSource_1 = response.data.list;
            } else {
              this.$exception(response);
            }
          })
        }
        return
      } else if (tabKey === '4' && this.bind) {
        if (this.Equipment.transferData == null) {
          this.Equipment.transferData = [];
          getPopDevice(this, {
            pageSize: 9999,
            pageNum: 1,
          }).then((res) => {
            if (res.success) {
              this.Equipment.transferData = res.data.list.map((item) => {
                return {
                  key: item.id,
                  title: item.name,
                  description: '',
                  ...item,
                };
              });
            }
          });
          this.dataSource_4=[]
           this.axios({ url: this.Equipment.url, method: 'post', data: { vehicleId: record.id, pageSize: 9999, pageNum: 1 } })
          .then((response) => {
            if (response.success) {
              this.dataSource_4 = response.data.list;
            } else {
              this.$exception(response);
            }
          })
        }
        return

      } else if (tabKey === '5' && this.bind) {
        if (this.container.transferData == null) {
          this.container.transferData = [];
          getPopContainer(this, {
            pageSize: 9999,
            pageNum: 1,
          }).then((res) => {
            if (res.success) {
              this.container.transferData = res.data.list.map((item) => {
                return {
                  key: item.id,
                  title: item.name,
                  description: '',
                  ...item,
                };
              });
            }
          });
          this.dataSource_5 = [];
            this.axios({ url: this.container.url, method: 'post', data: { vehicleId: record.id, pageSize: 9999, pageNum: 1 } })
          .then((response) => {
            if (response.success) {
              this.dataSource_5 = response.data.list;
            } else {
              this.$exception(response);
            }
          })
        }

        return

      }
      if (record && record.id) {
        let params = {
          1: { vehicleId: record.id },
          2: { vehicleId: record.id },
          3: { vehicleId: record.id },
          4: { vehicleId: record.id },
          5: { vehicleId: record.id },
        };
        try {
          this.$nextTick(() => {
            this.refTable && this.refTable.reload({ data: params[+tabKey] });
          });
        } catch (err) {
          console.error('tabKey:' + tabKey);
          throw new Error(err);
        } finally {
        }
      }
    },
    reload(args) {
      return this.refTable.reload(args);
    },
    remoteBefore(vNode, remoteUrl) {
      let searchBar = this.$parent.$parent.$parent.$refs.searchBar;
      if (searchBar) {
        const { getFieldsValue } = searchBar;
        remoteUrl.data = { ...remoteUrl.data, ...getFieldsValue() };
      }
    },
    handleDataAutoChange(targetKeys, direction, moveKeys) {

      this.targetKeys = targetKeys;
    },
    getTabsList() {
      let o = {
        //容器
        vehicleContainerLinks: this.filterContainerData(),
        //设备
        vehicleDeviceLinks: this.filterEquipmentData(),
        //司机
        vehicleDriverLinks: this.filterVehicleData(),
        //证件
        vehiclePaperLinks: this.dataSource_3.map((item) => {
          if (item.id.indexOf('new') > -1) {
            item.id = '';
          }
          return item;
        }),
      };
      return o;
    },

    //证证新增
    add_card() {
      this.visible = true;
      this.card_view = 1;
      this.card_title = '新增证件';
      this.card_data = null;
    },

    show_info_item(record) {
      this.card_view = 3;
      this.visible = true;
      this.card_title = '查看证件';
      this.card_data = record;
    },
    update_item(record) {
      this.card_view = 2;
      this.visible = true;
      this.card_title = '修改证件';
      this.card_data = record;
    },
    handle_ok(...ages) {
      //true:缓存数据跟主表一起保存，//false:直接调接口保存提交
      return this.btnSave ? this.cache_item(...ages) : this.save_item(...ages);
    },
    async cache_item(submit, close) {
      let values = await submit();
      //证件资料
      if (values) {
        if (this.card_view === 2) {
          let index = this.dataSource_3.findIndex((item) => item.id === values.id);
          if (index > -1) {
            this.dataSource_3[index] = values;
          }
        } else if (this.card_view === 1) {
          // values.id = 'new_' + (+new Date())
          this.dataSource_3.unshift(values);
        }

        this.visible = false;
      }
      close();
    },
    filterEquipmentData() {
      let arr = [];
      this.Equipment?.targetKeys?.length > 0 &&
        this.Equipment?.transferData?.filter((item) => {
          if (this.Equipment.targetKeys.indexOf(item.id) > -1) {
            arr.push({
              deviceCode: item.code,
              deviceId: item.id,
              deviceName: item.name,
            });
          }
        }, this);
      return arr;
    },
    filterContainerData() {
      let arr = [];
      this.container?.targetKeys?.length > 0 &&
        this.container?.transferData?.filter((item) => {
          if (this.container.targetKeys.indexOf(item.id) > -1) {
            arr.push({
              containerCode: item.code,
              containerId: item.id,
              containerName: item.name,
            });
          }
        }, this);
      return arr;
    },
    filterVehicleData() {
      let arr = [];

      this.transferData?.filter((item) => {
        if (this.targetKeys.indexOf(item.driverId) > -1) {
          let _item = { ...item };
          delete _item.key;
          delete _item.title;
          delete _item.description;
          delete _item._row_count;
          arr.push(_item);
        }
      }, this);
      return arr;
    },
    async save_item(submit, close) {
      let values = await submit();
      if (!this.currentMainRow) return;
      if (values === null) return close();

      const data = {
        plateNumber: this.currentMainRow.plateNumber,
        vehicleId: this.currentMainRow.id,
        vehicleCode: this.currentMainRow.code,
        vehicleName: this.currentMainRow.name,
        ...values,
      };

      return savePaper(this, this.card_view, data).then(() => {
        //close()
        this.visible = false;
        close();
        this.reload({ data: { vehicleId: this.currentMainRow.id } }).then(() => {
          this.refTable.activeID = values.id;
        });
      });
    },
    toggle_item(record) {
      // if (this.btnSave) {
      //   record.status = +(!record.status)
      //   return
      // }
      // {"vehiclePaperIds":[11,22,33],"status":"0"}

      let status = +!record.status;
      return paperIsEnable(this, [{ id: record.id }], status, this.currentMainRow.id).then(() => {
        this.$refs.table_3.activeID = record.id;
      });
    },

    isEnable_item(number) {
      let arr = this.selectedRowKeys_3.map((id) => {
        return { id };
      });
      return paperIsEnable(this, arr, number, this.currentMainRow.id);
    },
  },
};
</script>
