/*
 *@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="activeKey === '1' && !bind && st !== 3" :disabled="selectedRowKeys_1.length === 0" @clickSync="removeVehicle(null)">删除</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>
      <!-- :selectedRowKeys.sync="selectedRowKeys_1" -->

      <a-tab-pane :key="'1'" :tab="bind ? '绑定车辆' : '已绑车辆'">
        <transfer-table v-if="bind" :columns="bindCarColumns" :transferData="transferData" :targetKeys="targetKeys" :loading="confirmLoading" @change="handleDataAutoChange" />
        <t-table
          v-show="!bind"
          :pagination="false"
          rowKey="vehicleId"
          :dataSource.sync="dataSource_1"
          @selectChange="(selectKey, selectData)=>selectedRowKeys_1=selectKey"
          :scroll="{ x: true }"
          :vScrollX="{enabled: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' }"
          dragle
          :rowSelectType="2"
        >
          <template slot="operation" slot-scope="text, record">
            <a href="javascript:;" @click.stop="removeVehicle(record)">删除</a>
          </template>
        </t-table>
      </a-tab-pane>
      <a-tab-pane :key="'2'" tab="常跑线路">
        <t-table
          :scroll="{ x: true }"
          :id="$route.name + '_tabTable_2'"
          rowKey="lineId"
          ref="table_2"
          :autoLoad="false"
          @selectChange="(selectKey, selectData)=>selectedRowKeys_2=selectKey"
          :vScrollY="{enabled:true,rows:8}"
          bordered
          :columns="carLinkColumns"
          :remoteUrl="{ url: getLinkUrl, method: 'post',data:{vehicleId:currentMainRow&&currentMainRow.id}   }"
          dragle
          :rowSelectType="0"
        ></t-table>
      </a-tab-pane>
      <a-tab-pane :key="'3'" tab="证件资料">
        <t-table
          :id="$route.name + '_tabTable_3'"
          :autoLoad="false"
          @selectChange="(selectKey, selectData)=>selectedRowKeys_3=selectKey"
          :vScrollY="{enabled:true,rows:8}"
          :scroll="{ x: true }"
          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 v-if="st !== 3" type="vertical" />
            <a v-if="st !== 3" href="javascript:;" @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-tab-pane  v-if="$auth('bms')&&!bind" key="4" tab="基础费用">
        <transfer-table
          :talbeTitle="['待分配费用', '已分配费用']"
          :columns="bindBMSColumns"
          :transferData="currentMainRow?transferBMSData:[]"
          :targetKeys="targetBMSKeys"
          :loading="confirmLoading"
          @change="handleBMSAutoChange"
        />
        <!-- <p-table
          v-else
          rowKey="id"
          :dataSource.sync="dataSource_4"
          :scroll="{ x: true }"
          :id="$route.meta.menuId + '_tabTable_4'"
          ref="table_4"
          :autoLoad="false"
          bordered
          :columns="bindBMSColumns"
          :remoteUrl="{ url: getBMSUrl, method: 'post' }"
          dragle
          :rowSelectType="false"
        >
        </p-table> -->
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script>
import { bindCarColumns, carManColumns, carLinkColumns, certificateColumns, bindBMSColumns } from './setConfig.js';
import { costFeeSave, removeVehicle, paperIsEnable, savePaper, costList, getBindCarUrl, getLinkUrl, getCertificateUrl, removeCard, getBindAll, getBMSUrl } 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,
    },
    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 {
      confirmLoading: false,
      activeKey: this.tabActive,
      getBindCarUrl,
      getLinkUrl,
      getBMSUrl,
      getCertificateUrl,
      bindBMSColumns: bindBMSColumns(this), //绑定基础费用
      bindCarColumns: bindCarColumns(this), //绑定司机
      carManColumns: carManColumns(this), //已绑司机
      carLinkColumns: carLinkColumns(this),
      certificateColumns: certificateColumns(this),
      transferBMSData: [],
      targetBMSKeys: [],

      transferData:void 0, //绑定车辆数据
      targetKeys: [],
      card_show: false,
      visible: false,
      card_title: '',
      card_view: 0,
      card_data: null,
      dataSource_1: [],
      dataSource_2: [],
      selectedRowKeys_1: [],
      dataSource_3: [],
      selectedRowKeys_3: [],

      dataSource_4: [],
      selectedRowKeys_4: [],
    };
  },
  watch: {
    clearAll(is) {
      if (is) {
        this.dataSource_1 = [];
        this.dataSource_2 = [];
        this.dataSource_3 = [];
        this.dataSource_4 = [];
      }
    },
    dataSource_1(v) {
      this.targetKeys = v.map((item) => {
        return item.vehicleId;
      });
    },
    st(value) {
      if (value === 0) {
        this.card_view = value;
        this.updateActiveTab(this.activeKey, this.currentMainRow);
      } else if (value === 1) {
        this.dataSource_1 = [];
        this.dataSource_2 = [];
        this.dataSource_3 = [];
        this.dataSource_4 = [];
        this.updateActiveTab('1', null);
      }
    },
    currentMainRow(record) {
      this.dataSource_1 = [];
      this.dataSource_2 = [];
      this.dataSource_3 = [];
      this.dataSource_4 = [];
      this.targetBMSKeys = [];
      if (record) {
        this.updateActiveTab(this.activeKey, record);
      }
    },
    activeKey(tabKey) {
      this.updateActiveTab(tabKey, this.currentMainRow);
    },
  },
  computed: {
    refTable() {
      return this.$refs['table_' + this.activeKey];
    },
  },
  mounted() {
    //基础费用
    !this.bind &&
      costList(this, { code: '', dataType: 3 })?.then((res) => {
        if (res.success) {
          this.transferBMSData = res.data.map((item) => {
            return {
              key: item.expenseCode,
              title: item.expenseName,
              description: item.id,
              ...item,
            };
          });
        }
      });
  },
  methods: {
    handleBMSAutoChange(targetKeys, direction, moveKeys) {
      if (!this.currentMainRow) return;

      return costFeeSave(this, {
        code: this.currentMainRow.code,
        list: this.transferBMSData.filter((item) => {
          item.dataType = 3;
          return targetKeys.includes(item.expenseCode);
        }),
      })
        .then((data) => {
          if (data) {
            this.targetBMSKeys = targetKeys;
          }
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    removeVehicle(record) {
      const { id } = this.currentMainRow;
      let arr = [];
      if (!record) {
        this.dataSource_1.forEach((item) => {
          if (this.selectedRowKeys_1.indexOf(item.vehicleId) > -1) {
            arr.push({ driverId: id, vehicleId: item.vehicleId });
          }
        }, this);
      } else {
        arr = [{ driverId: id, vehicleId: record.vehicleId }];
      }
      return removeVehicle(this, arr, id);
    },
    updateActiveTab(tabKey, record) {
      if (tabKey === '1' && this.bind) {
        //获取所有车辆数据
        if (typeof this.transferData == 'undefined') {
          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.plateNumber,
                description: item.typeName,
                vehicleId: item.id,
                vehicleCode: item.code,
                vehiclePlateNumber: item.plateNumber,
                vehicleTypeName: item.typeName,
                ...item,
              };
            });
          }
        });
        }

      } else if (tabKey === '4' && !this.bind) {

        this.targetBMSKeys = [];
        if (record) {
          this.confirmLoading = true;
         return costList(this, { dataType: 3, code: record.code })?.then((res) => {
              if (res.success && res.data.length > 0) {
                this.targetBMSKeys = res.data.map((item) => {
                  return item.expenseCode;
                });
              }
            }).finally(() => {
              this.confirmLoading = false;
            })
        }
      }

      if (record && record.id) {
        let params = [{}, { id: record.id, whether: 1 }, { id: record.id }, { id: record.id }, { dataType: 3, code: record.code }];
        try {
          this.$nextTick(() => {
            this.refTable && this.refTable.reload({ data: params[+tabKey] });
          });
        } catch (err) {
          console.error('tabKey:' + tabKey);
          throw new Error(err);
        } finally {
        }
      } else {
        //this.refTable.tData = []
      }
    },
    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() {
      return {
        driverVehicleLinks: this.filterVehicleData(),
        driverPaperLinks: this.dataSource_3.map((item) => {
          if (item.id.indexOf('new') > -1) {
            item.id = '';
          }
          return item;
        }),
      };
    },

    //证证新增
    add_card() {
      this.visible = true;
      this.card_view = 1;
      this.card_title = '新增证件';
      this.card_data = null;
    },
    delete_card(record) {
      //   alert('开发中...');
      let data = [];
      let { id } = this.currentMainRow || {};
      if (record === null) {
        this.selectedRowKeys_3.forEach((key) => {
          data.push({ driverId: id, paperId: key });
        });
      } else {
        data = [{ driverId: id, paperId: record.id }];
      }
      removeCard(this, data, id);
    },
    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);
        }
        //close()

        this.visible = false;
      }
    },
    filterVehicleData() {
      let arr = [];
      this.transferData.filter((item) => {
        if (this.targetKeys.indexOf(item.vehicleId) > -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 = {
        driverId: this.currentMainRow.id,
        driverCode: this.currentMainRow.code,
        driverName: this.currentMainRow.name,
        ...values,
      };

      return savePaper(this, this.card_view, data).then(() => {
        //close()
        this.visible = false;
        this.reload({ data: { id: this.currentMainRow.id } }).then(() => {
          this.refTable.activeID = values.id;
        });
      });
    },
    toggle_item(record) {
      // if (this.btnSave) {
      //   record.status = +(!record.status)
      //   return
      // }
      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>
