<!--
@name: 线路管理-tab页-首页使用
@author: 张泽贤
@time: 2022-10-10
@doc: PROLOG_UPCloudSolutionForTMS__v1.2.1_PC+小程序优化版本_1.3.9_v3.doc
-->
<template>
  <p-spin :spinning="spinning">
    <p-card>
      <p-tabs :animated="false" :activeKey="activeKey" @tabClick="activeKey = $event">
        <p-tab-pane key="1" tab="发货方信息" :forceRender="true">
          <!-- 列表展示 -->
          <p-table
            v-show="editData.startLineType === 1"
            ref="shipperTable"
            dragle
            bordered
            row-key="branchId"
            :scroll="{ x: true }"
            :data-source.sync="shipper_dataSource"
            :remote-url="shipper_listRemoteUrl"
            :remoteData="shipper_listParams"
            :rowSelectType="false"
            :selectedRowKeys.sync="shipper_selectedRowKeys"
            :autoLoad="false"
            :pagination="false"
          >
            <p-table-column data-index="pickupOrder" title="提货顺序" :width="120" />
            <p-table-column data-index="branchCode" title="仓库编码" :width="120" />
            <p-table-column data-index="branchName" title="仓库名称" :width="120" />
            <p-table-column data-index="contact" title="联系人" :width="120" />
            <p-table-column data-index="contactTel" title="联系方式" :width="120" />
            <p-table-column data-index="address" title="详细地址" :width="120" />
          </p-table>
          <p-tree
            v-show="editData.startLineType === 2"
            :checkedKeys="shipper_checkedKeys"
            checkable
            :tree-data="shipper_treeData"
            :load-data="(treeNode) => onLoadData(treeNode, 'shipper')"
            disabled
            :replaceFields="{
              children: 'children',
              title: 'zname',
              key: 'zoneid',
            }"
            :expandedKeys.sync="shipper_expandedKeys"
            :loadedKeys="shipper_loadedKeys"
            @load="shipper_onLoad"
          />
        </p-tab-pane>
        <p-tab-pane key="2" tab="收货方信息" :forceRender="true">
          <!-- 列表展示 -->
          <p-table
            v-show="editData.distinguishType === 1"
            ref="consigneeTable"
            dragle
            bordered
            row-key="consigneeId"
            :id="$route.meta.menuId + '_consignee'"
            :scroll="{ x: true }"
            :data-source.sync="consignee_dataSource"
            :remote-url="consignee_listRemoteUrl"
            :remoteData="consignee_listParams"
            :rowSelectType="false"
            :selectedRowKeys.sync="consignee_selectedRowKeys"
            :autoLoad="false"
            :pagination="false"
          >
            <p-table-column data-index="customerCode" title="客户编码" :width="120" />
            <p-table-column data-index="customerName" title="客户名称" :width="120" />
            <p-table-column data-index="consigneeCode" title="收货方编码" :width="120" />
            <p-table-column data-index="consigneeName" title="收货方名称" :width="120" />
            <p-table-column data-index="consigneeContact" title="联系人" :width="120" />
            <p-table-column data-index="consigneePhoneNumber" title="联系地址" :width="120" />
            <p-table-column data-index="consigneeAddress" title="收货方地址" :width="120" />
            <p-table-column data-index="consigneeMemo" title="收货方备注" :width="120" />
            <p-table-column data-index="deliveryOrder" title="配送顺序" :width="120" />
          </p-table>
          <p-tree
            v-show="editData.distinguishType === 2"
            :checkedKeys="consignee_checkedKeys"
            checkable
            :tree-data="consignee_treeData"
            :load-data="(treeNode) => onLoadData(treeNode, 'consignee')"
            disabled
            :replaceFields="{
              children: 'children',
              title: 'zname',
              key: 'zoneid',
            }"
            :expandedKeys.sync="consignee_expandedKeys"
            :loadedKeys="consignee_loadedKeys"
            @load="consignee_onLoad"
          />
        </p-tab-pane>
        <p-tab-pane key="3" tab="承运方信息" :forceRender="true">
          <!-- 列表展示 -->
          <p-table
            ref="carrierTable"
            dragle
            bordered
            row-key="carrierId"
            :scroll="{ x: true }"
            :data-source.sync="carrier_dataSource"
            :remote-url="carrier_listRemoteUrl"
            :remoteData="carrier_listParams"
            :rowSelectType="false"
            :selectedRowKeys.sync="carrier_selectedRowKeys"
            :autoLoad="false"
          >
            <p-table-column data-index="carrierCode" title="承运方编码" :width="120" />
            <p-table-column data-index="carrierName" title="承运方名称" :width="120" />
            <p-table-column data-index="phoneNumber" title="手机号" :width="120" />
            <p-table-column data-index="vehiclePlateNumber" title="车牌号" :width="120" />
            <p-table-column data-index="shares" title="份额" :width="120" />
          </p-table>
        </p-tab-pane>
        <p-tab-pane key="4" tab="线路可用日期" :forceRender="true">
          <p-spin :spinning="dateSpinning">
            <p-form-model ref="dateForm" class="plg-grid-from availableDate" :model="availableDate" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <!-- <a-row>
              <a-col :span="24">
                <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: right">
                  <a-space>
                    <p-button type="primary" @clickSync="onDataSave" :disabled="!editData.lineId">保存</p-button>
                  </a-space>
                </p-form-model-item>
              </a-col>
            </a-row> -->
              <a-row style="margin-bottom: 30px">
                <a-col :span="12">
                  <p-checkbox :indeterminate="weekIndeterminate" :checked="weekAll" @change="onWeekAllChange" disabled>全部</p-checkbox>
                  <br />
                  <p-checkbox-group v-model="selectWeek" :options="weekList" @change="onWeekChange" disabled />
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="12">
                  <p-checkbox :indeterminate="dayIndeterminate" :checked="dayAll" @change="onDayAllChange" disabled>全部</p-checkbox>
                  <p-checkbox :indeterminate="singleIndeterminate" :checked="singleAll" @change="onSingleAllChange" disabled>单号</p-checkbox>
                  <p-checkbox :indeterminate="doubleIndeterminate" :checked="doubleAll" @change="onDoubleAllChange" disabled>双号</p-checkbox>
                  <br />
                  <p-checkbox-group v-model="selectDay" :options="dayList" @change="onDayChange" disabled />
                </a-col>
              </a-row>
            </p-form-model>
          </p-spin>
        </p-tab-pane>
        <p-tab-pane key="5" tab="途径点" :forceRender="true" v-if="$auth('waypoint')">
          <p-table
            ref="waypointTable"
            dragle
            bordered
            row-key="siteOrder"
            :scroll="{ x: true }"
            :data-source.sync="waypoint_dataSource"
            :remote-url="waypoint_listRemoteUrl"
            :remoteData="waypoint_listParams"
            :rowSelectType="false"
            :autoLoad="false"
          >
            <p-table-column data-index="siteOrder" title="站点顺序" />
            <p-table-column data-index="siteTypeName" title="站点类型" />
            <p-table-column data-index="typeName" title="类型" />
            <p-table-column data-index="siteCode" title="编码" />
            <p-table-column data-index="siteName" title="名称" />
            <p-table-column data-index="address" title="详细地址" />
            <p-table-column data-index="shipperAgingTime" title="发货时间" :width="120" />
            <p-table-column data-index="shipperAgingTimeLineName" title="发货时间类型" :width="120" />
            <p-table-column data-index="consigneeAgingTime" title="到货时间" :width="120" />
            <p-table-column data-index="consigneeAgingTimeLineName" title="到货时间类型" :width="120" />
          </p-table>
        </p-tab-pane>
      </p-tabs>
    </p-card>
  </p-spin>
</template>

<script>
import * as $formItems from '@/blocks/components/searchModalConfig/index';

import { shipper_listRemoteUrl, consignee_listRemoteUrl, carrier_listRemoteUrl, getByPid, dateQuery, dateSave, waypoint_listRemoteUrl, View } from '../js/api.js';

export default {
  props: {
    editId: {
      type: String,
      default: '',
    },
  },
  watch: {
    editId: {
      handler(val) {
        if (val) {
          this.tabSearch(val);
        } else {
          this.tabReset();
        }
      },
    },
  },
  data() {
    return {
      $formItems,
      activeKey: '1',
      dateSpinning: false,
      editData: {},
      spinning: false,

      // 收货方-仓库表格
      shipper_dataSource: [],
      shipper_selectedRowKeys: [],
      shipper_listRemoteUrl,
      shipper_listParams: {},

      // 收货方树
      shipper_checkedKeys: [],
      shipper_treeData: [],

      // 发货方表格
      consignee_dataSource: [],
      consignee_selectedRowKeys: [],
      consignee_listRemoteUrl,
      consignee_listParams: {},

      // 发货方树
      consignee_checkedKeys: [],
      consignee_treeData: [],

      // 承运方表格
      carrier_dataSource: [],
      carrier_selectedRowKeys: [],
      carrier_listRemoteUrl,
      carrier_listParams: {},

      // 线路可用日期
      availableDate: {},
      weekIndeterminate: false,
      weekAll: false,
      weekList: [
        { value: 'week_1', label: '星期一' },
        { value: 'week_2', label: '星期二' },
        { value: 'week_3', label: '星期三' },
        { value: 'week_4', label: '星期四' },
        { value: 'week_5', label: '星期五' },
        { value: 'week_6', label: '星期六' },
        { value: 'week_7', label: '星期日' },
      ],
      selectWeek: [],
      dayIndeterminate: false,
      singleIndeterminate: false,
      doubleIndeterminate: false,
      dayAll: false,
      singleAll: false,
      doubleAll: false,
      dayList: [],
      singleList: [],
      doubleList: [],
      selectDay: [],

      // 途径点
      waypoint_dataSource: [],
      waypoint_listRemoteUrl,
      waypoint_listParams: {},

      shipper_expandedKeys: [],
      shipper_loadedKeys: [],
      consignee_expandedKeys: [],
      consignee_loadedKeys: [],
    };
  },
  mounted() {
    getByPid({ fatherid: '01' }).then((res) => {
      this.shipper_treeData = [...res.data];
      this.consignee_treeData = [...res.data];
    });
    for (let index = 1; index < 32; index++) {
      if (index % 2 === 0) {
        this.doubleList.push(index + '');
      } else {
        this.singleList.push(index + '');
      }
      this.dayList.push(index + '');
    }
  },
  methods: {
    // tab页查询
    tabSearch(lineId) {
      this.spinning = true;
      View({ lineId })
        .then((res) => {
          this.editData = { ...res.data };
          if (this.editData.startLineType === 1 && this.editData.tmsShipperDTOs) {
            this.shipper_dataSource = this.editData.tmsShipperDTOs;
          } else {
            this.shipper_dataSource = [];
          }
          if (this.editData.distinguishType === 1 && this.editData.tmsArriverDTOs) {
            this.consignee_dataSource = this.editData.tmsArriverDTOs;
          } else {
            this.consignee_dataSource = [];
          }
          // this.shipper_dataSource = this.editData.tmsShipperDTOs ? this.editData.tmsShipperDTOs : [];
          // this.consignee_dataSource = this.editData.tmsArriverDTOs ? this.editData.tmsArriverDTOs : [];

          if (this.editData.shipperAdministrativeAreas) {
            this.updateTree(this.editData.shipperAdministrativeAreas, 'shipper');
          } else {
            this.shipper_checkedKeys = [];
          }
          if (this.editData.administrativeAreas) {
            this.updateTree(this.editData.administrativeAreas, 'consignee');
          } else {
            this.consignee_checkedKeys = [];
          }
        })
        .finally(() => {
          this.spinning = false;
        });

      // 列表状态查询
      // console.log(lineId);
      // this.shipper_listParams = { lineId };
      // this.consignee_listParams = { lineId };
      this.carrier_listParams = { lineId };
      this.dateQuery();
      this.waypoint_listParams = { lineId };
    },
    // 重置
    tabReset() {
      this.editData = {};
      this.shipper_dataSource = [];
      this.shipper_checkedKeys = [];
      this.consignee_dataSource = [];
      this.consignee_checkedKeys = [];
      this.carrier_dataSource = [];
      this.waypoint_dataSource = [];
      this.dateReset();
    },
    // 可用时间重置
    dateReset() {
      this.selectDay = [];
      this.weekIndeterminate = false;
      this.weekAll = false;
      this.selectWeek = [];
      this.dayIndeterminate = false;
      this.singleIndeterminate = false;
      this.doubleIndeterminate = false;
      this.dayAll = false;
      this.singleAll = false;
      this.doubleAll = false;
    },

    // 途径点地图
    onMap() {
      this.$emit('onMap');
    },

    // 线路可用日期
    onWeekChange(checkedList) {
      this.weekIndeterminate = !!checkedList.length && checkedList.length < this.weekList.length;
      this.weekAll = checkedList.length === this.weekList.length;
    },
    onWeekAllChange(e) {
      Object.assign(this, {
        selectWeek: e.target.checked ? this.weekList.map((item) => item.value) : [],
        weekIndeterminate: false,
        weekAll: e.target.checked,
      });
    },
    onDayChange(checkedList) {
      this.dayAll = checkedList.length === this.dayList.length;
      this.singleAll = this.equar(checkedList, this.singleList);
      this.doubleAll = this.equar(checkedList, this.doubleList);
    },
    onDayAllChange(e) {
      Object.assign(this, {
        selectDay: e.target.checked ? this.dayList : [],
        dayIndeterminate: false,
        dayAll: e.target.checked,
        singleAll: false,
        doubleAll: false,
      });
    },
    onSingleAllChange(e) {
      let singleList = [];
      this.dayList.forEach((item) => {
        if (item % 2 === 1) {
          singleList.push(item);
        }
      });
      Object.assign(this, {
        selectDay: e.target.checked ? singleList : [],
        singleIndeterminate: false,
        dayAll: false,
        singleAll: e.target.checked,
        doubleAll: false,
      });
    },
    onDoubleAllChange(e) {
      let doubleList = [];
      this.dayList.forEach((item) => {
        if (item % 2 === 0) {
          doubleList.push(item);
        }
      });
      Object.assign(this, {
        selectDay: e.target.checked ? doubleList : [],
        doubleIndeterminate: false,
        dayAll: false,
        singleAll: false,
        doubleAll: e.target.checked,
      });
    },
    // 校验数组是否相同
    equar(a, b) {
      // 判断数组的长度
      if (a.length !== b.length) {
        return false;
      } else {
        a = this.compare(a);
        b = this.compare(b);
        // 循环遍历数组的值进行比较
        for (let i = 0; i < a.length; i++) {
          if (a[i] !== b[i]) {
            return false;
          }
        }
        return true;
      }
    },
    // 排序
    compare(p) {
      return function (m, n) {
        var a = m[p];
        var b = n[p];
        return a - b; //升序
      };
    },
    // 查询线路可用日期
    dateQuery() {
      this.dateReset();
      this.dateSpinning = true;
      dateQuery({ lineId: this.editId })
        .then((res) => {
          for (const key in res.data.days) {
            if (res.data.days[key] === '1') {
              this.selectDay.push(key.split('_')[1]);
            }
          }
          this.dayAll = this.selectDay.length === 31;
          this.singleAll = this.equar(this.selectDay, this.singleList);
          this.doubleAll = this.equar(this.selectDay, this.doubleList);
          for (const key in res.data.weeks) {
            if (res.data.weeks[key] === '1') {
              this.selectWeek.push(key);
            }
          }
          this.weekIndeterminate = this.selectWeek.length > 0 && this.selectWeek.length < 7;
          this.weekAll = this.selectWeek.length === 7;
        })
        .finally(() => {
          this.dateSpinning = false;
        });
    },
    // 线路可用日期保存
    onDataSave() {
      let request = {
        lineId: this.editId,
        days: {},
        weeks: {},
      };
      this.dayList.forEach((item) => {
        request.days['day_' + item] = this.selectDay.includes(item) ? '1' : '0';
      });
      this.weekList.forEach((item) => {
        request.weeks[item.value] = this.selectWeek.includes(item.value) ? '1' : '0';
      });

      this.dateSpinning = true;
      dateSave(request)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.dateSpinning = false;
        });
    },

    onLoadData(treeNode, name) {
      return new Promise((resolve) => {
        // console.log(treeNode.dataRef);
        if (treeNode.dataRef.zlevel === 5) {
          resolve();
          return;
        }
        getByPid({ fatherid: treeNode.dataRef.zoneid }).then((res) => {
          treeNode.dataRef.children = [...res.data];
          this[name + '_treeData'] = [...this[name + '_treeData']];
          resolve();
        });
      });
    },

    shipper_onLoad(loadedKeys) {
      this.shipper_loadedKeys = loadedKeys;
    },
    consignee_onLoad(loadedKeys) {
      this.consignee_loadedKeys = loadedKeys;
    },

    updateTree(list, name) {
      // console.log(list, name);
      let parent = new Set();
      list.forEach((item) => {
        parent.add(item.substring(0, 2) + '0000');
        parent.add(item.substring(0, 4) + '00');
      });
      let parentList = [...parent];

      getByPid({ fatherid: parentList.join(',') }).then((res) => {
        let cityObj = {},
          districtList = [];
        res.data.forEach((item) => {
          if (item.zlevel === 3) {
            item.children = [];
            cityObj[item.zoneid] = item;
          } else {
            districtList.push(item);
          }
        });
        districtList.forEach((item) => {
          cityObj[item.fatherid].children.push(item);
        });
        this[name + '_treeData'].forEach((item1) => {
          item1.children = [];
          for (const key in cityObj) {
            const item2 = cityObj[key];
            if (item1.zoneid === item2.fatherid) {
              item1.children.push(item2);
            }
          }
        });

        this[name + '_expandedKeys'] = parentList;
        this[name + '_checkedKeys'] = list;
        // console.log(this[name + '_expandedKeys']);
        // console.log(this[name + '_checkedKeys']);
      });
    },
  },
};
</script>

<style lang="less">
.availableDate {
  .ant-checkbox-wrapper {
    width: 70px;
  }
}

.dis-flex {
  display: flex;
  .flex-table {
    width: 49%;
    // flex: 1;
  }
  .flex-btn {
    width: 30px;
    padding-top: 100px;
    // height: 300px;
    // line-height: 300px;
  }
}
</style>