<template>
  <div class="SetLogisticsArea">

    <div class="logisticsCompanyArea">
      <div class="logisticsSearch">
        <Input
          v-model="logisticsCompanySearch"
          suffix="ios-search"
          placeholder=""
          style="width: 100%;"
          @on-enter="getLogisticsCompanyList()"
          @on-click="getLogisticsCompanyList()"
        />
      </div>
      <div class="logisticsCompanyBox">
        <div
          v-for="(item,index) in logisticsCompanyList"
          :key="index"
          class="logisticsItem"
          :class="item.id == choosedLogisticsCompany.id?'itemactive':''"
          @click="companyClick(item)"
        >
          <span>{{ item.logisticsCompanyName }}</span>
        </div>
      </div>
    </div>
    <div class="logisticsCompanySetArea">
      <Spin fix v-if="loading">
        <div class="loader">
          <svg class="circular" viewBox="25 25 50 50">
            <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="5" stroke-miterlimit="10"></circle>
          </svg>
        </div>
        <div>正在加载，请稍后...</div>
      </Spin>
      <div class="quickOperation quickOperationOne">
        <Button
          type="fcdefault"
          style="margin-right:8px"
          @click="saveAll"
        >
          保存
        </Button>
        <Button
          type="fcdefault"
          style="margin-right:8px"
          @click="refreshParams"
        >
          刷新
        </Button>
        <span @click="clickHelp" >
          <span title="帮助中心">
            <i class='ark-icon ark-icon iconfont iconios-help-circle-outline' style="font-size: 26px;opacity: 0.7;color: var(--primary-color);"></i>
          </span>
        </span>
      </div>
      <div class="baseMsg">
        <foldPanel
          title="基础信息"
        >
          <div
            slot="content"
            class="block"
          >
            <Form
              :label-width="80"
              label-position="left"
              inline
            >
              <div class="choosedCompanyName">
                {{ choosedLogisticsCompany.logisticsCompanyName }}
              </div>
              <FormItem label="支持范围：">
                <RadioGroup
                  v-model="supportScope"
                  @on-change="changeSupportScope"
                >
                  <Radio label="0">
                    <span>全部（包含港澳台和海外地址）</span>
                  </Radio>
                  <Radio label="1">
                    <span>自定义</span>
                  </Radio>
                </RadioGroup>
              </FormItem>
            </Form>
          </div>
        </foldPanel>
      </div>
      <div class="setContentArea">
        <foldPanel
          :title="setAreaTitle"
        >
          <div
            slot="content"
            class="block"
          >
            <div class="quickOperation">
              <Button
                v-if="!isAllArea"
                type="fcdefault"
                style="margin-right:8px"
                @click="addArea"
              >
                添加省
              </Button>
              <Button
                type="fcdefault"
                style="margin-right:8px"
                @click="excludedArea"
              >
                排除省市区
              </Button>
              <Button
                type="fcdefault"
                style="margin-right:8px"
                @click="deleteArea"
              >
                删除区域
              </Button>
              <Button
                type="fcdefault"
                style="margin-right:8px"
                @click="importArea"
              >
                导入
              </Button>
            </div>
            <Table
              height="400" 
              :columns="AreaColumns" 
              :data="currentAreaData"
              @on-select="selectAreaData"
              @on-select-cancel="selectAreaCancel"
              @on-select-all="selectAreaDataAll"
              @on-select-all-cancel="selectAreaDataCancel"
            />
            <div class="pageContent">
              <Page
                size="small"
                :current="AreaCurrentPage"
                :page-size="pageSizeArea"
                show-elevator
                :total="totalArea"
                show-total
                show-sizer
                @on-change="changePageArea"
                @on-page-size-change="changeSizeArea"
              />
            </div>
          </div>
        </foldPanel>
      </div>
    </div>
    <!-- 添加配送省份弹框 -->
    <Modal
      v-model="addAreaModal"
      mask
      :mask-closable="maskClosable"
      :closable="closable"
      :footer-hide="hideFoot"
      title="添加配送省份"
      title-align="left"
      class-name="addAreaModal"
      width="600px"
      @on-cancel="cancelAddArea"
    >
      <div class="choosedAreaProvince">
        <Form
          :model="formAddArea"
          :label-width="80"
        >
          <FormItem
            required
            label="配送省份"
          >
            <Select
              v-model="formAddArea.choosedProvinceList"
              label-in-value
              multiple
              clearable
              class="input_box"
              @on-change="changeAddArea($event)"
            >
              <Option
                v-for="d in provinceList"
                :key="d.value"
                :value="d.value"
              >
                {{ d.label }}
              </Option>
            </Select>
          </FormItem>
        </Form>
      </div>
      <footer style="display: flex; justify-content: center; margin-top: 12px;padding-top: 16px;border-top: 1px solid #DEDEDE;;">
        <Button
          type="fcdefault"
          @click="cancelAddArea"
        >
          取消
        </Button>
        <Button
          type="posdefault"
          style="margin-left: 16px"
          @click="okAddArea"
        >
          确认
        </Button>
      </footer>
    </Modal>
    <!-- 添加排除区域弹框 -->
    <Modal
      v-model="excludedAreaModal"
      mask
      :mask-closable="maskClosable"
      :closable="closable"
      :footer-hide="hideFoot"
      title="添加排除区域"
      title-align="left"
      class-name="excludedAreaModal"
      width="700px"
      @on-cancel="cancelExcludedArea"
    >
      <div class="choosedAreaProvince">
        <Form
          :model="formExcludedArea"
          :label-width="90"
        >
          <FormItem
            required
            label="排除省份"
          >
            <Select
              v-model="formExcludedArea.choosedProvince"
              label-in-value
              clearable
              class="input_box"
              @on-change="changeExcludedArea($event)"
            >
              <Option
                v-for="d in provinceList"
                :key="d.value"
                :value="d.value"
              >
                {{ d.label }}
              </Option>
            </Select>
          </FormItem>
          <FormItem
            label="排除地区"
          >
            <div class="afterProvince">
              <div class="cityul">
                <p
                  v-for="(item,index) in cityList"
                  :key="index"
                >
                  <Checkbox
                    v-model="item.checked"
                    :value="item.value"
                    @on-change="cityChange(item,index)"
                  />
                  <span
                    class="cityItem"
                    :class="item.active?'cityActive':''"
                    @click="chooseCity(item,index)"
                  >{{ item.label }}</span>
                </p>
              </div>
              <div class="areaul">
                <p
                  v-for="(item,index) in areaList"
                  :key="index"
                >
                  <Checkbox
                    v-model="item.checked"
                    @on-change="chooseArea(item,index)"
                  >
                    {{ item.label }}
                  </Checkbox>
                </p>
              </div>
            </div>
          </FormItem>
          <FormItem
            label="排除具体街道"
          >
            <Input
              v-model="excludedSpecificArea"
              type="textarea"
              :rows="5"
              placeholder="请输入具体排除街道，多个用逗号、分号、空格分隔"
            />
          </FormItem>
        </Form>
      </div>
      <footer style="display: flex; justify-content: center; margin-top: 12px;padding-top: 16px;border-top: 1px solid #DEDEDE;;">
        <Button
          type="fcdefault"
          @click="cancelExcludedArea"
        >
          取消
        </Button>
        <Button
          type="posdefault"
          style="margin-left: 16px"
          @click="okExcludedArea"
        >
          确认
        </Button>
      </footer>
    </Modal>
    <LogisticsAreaImport :supportScope='supportScope' :pageMsgId='choosedLogisticsCompany.id' :visible='LogisticsAreaVisible' @closeActionDialog = 'closeActionAllDialog' ></LogisticsAreaImport>
    <!-- :pageMsgId='pageMsgId' -->
  </div>
</template>

<script>
  import foldPanel from '../customizedContent/FoldPanel.vue';
  import LogisticsAreaImport from '../modal/systemImport/LogisticsAreaImport.vue'; // 参与商品导入弹框

  const R3 = window.R3;
  const { network, urlSearchParams } = R3;
  export default {
    components: { foldPanel,LogisticsAreaImport},
    data() {
      return {
        LogisticsAreaVisible: false, // 导入（全国）
        loading: false,
        mask: true,
        closable: true,
        maskClosable: false,
        hideFoot: true,

        logisticsCompanySearch: '', // 物流公司搜索值
        choosedLogisticsCompany: '', // 左侧选中的物流公司
        logisticsCompanyList: [], // 物流公司列表数据
        setAreaTitle: '排除以下地区', // 设置区域title

        supportScope: '1', // 支持范围
        isAllArea: false, // 是否全国区域
        nationalOld: '', // 记录原始支持范围

        // 排除一下地区table的column
        AreaColumns: [ // 排除地区
          {
            type: 'selection',
            width: 60,
            align: 'center'
          }, 
          {
            type: 'index',
            align: 'center',
            title: '序号',
          },
          {
            title: '排除省份',
            align: 'center',
            key: 'province'
          },
          {
            title: '排除区域',
            align: 'center',
            key: 'excludedArea',
            width: 320,
            tooltip: true,
          },
          {
            title: '排除具体区域',
            align: 'center',
            key: 'excludedSpecificArea',
            width: 320,
            tooltip: true,
          },
          {
            title: '修改人',
            align: 'center',
            key: 'modifiedBy'
          },
          {
            title: '修改时间',
            align: 'center',
            key: 'modifiedTime'
          },
        ],
        currentAreaData: [], // 当前显示排除区域
        AreaData: [], // 所有设置区域数据
        submitArrArea: [], 

        // 区域page
        AreaCurrentPage: 1,
        totalArea: 0, // 总条数
        currentPageArea: 0, // 页码
        pageSizeArea: 10, // 每页的条数

        // 添加区域弹框
        addAreaModal: false,
        provinceList: [], // 省份列表
        formAddArea: {
          choosedProvinceList: [],
        }, // 添加区域
        // 排除区域弹框
        excludedAreaModal: false,
        formExcludedArea: {
          choosedProvince: '',
        },
        excludedProvince: '',
        cityList: [], // 市数据
        choosedCityArr: [], // 选择的市
        areaList: [], // 区数据
        choosedAreaArr: [], // 选择的区
        choosedCityAndAreaArr: [], // 选中的市和区组合
        excludedSpecificArea: '', // 排除具体区域
      };
    },
    created() {
      this.getLogisticsCompanyList();
      this.getProvinceList();
    },
    methods: {
      clickHelp() {
        this.triggerAjax();
        window.open('https://burgeon.yuque.com/cgmq7t/cgv53l/aeyn7e974kgxth06?singleDoc#');
      },
      // 请求埋点
      triggerAjax() {
        const params = {
          MENUNAME: '物流配送区域',
          BUTTONNAME: '点击帮助',
        };
        network.post('/p/cs/button/clickCount', params);
      },
      // 导入
      importArea() {
        this.LogisticsAreaVisible = true;
      },
      // 策略明细表导入弹框关闭
      closeActionAllDialog() {
        this.LogisticsAreaVisible = false;
      },
      /*
      *  getTreeIds() 递归当前点击的树层级下的所有regionId
      *  unique() 数组去重（可调用也可不调用）
      * */
      getTreeIds(data) {
        let regionIdList = [];
        data.forEach(item => {
          regionIdList.push(String(item.provinceId));
          if(item.excludedAreaList && item.excludedAreaList.length > 0){
            item.excludedAreaList.forEach(itemOne => {
              regionIdList.push(String(itemOne.cityId));
              if(itemOne.areaList && itemOne.areaList.length > 0){
                itemOne.areaList.forEach(itemTwo => {
                  regionIdList.push(String(itemTwo.value));
                })
              }
            })
          }
        })
        // this.unique(regionIdList)
        return regionIdList;
      },
      // 去重
      unique(arr) {
        const res = new Map();
        return arr.filter((arr) => !res.has(arr) && res.set(arr, 1));
      },
      refreshParams() {
        let flag = true;
        if(this.nationalOld == this.supportScope) {
          flag = false;
        }
        console.log(this.AreaDataOld)
        let AreaDataOldList  = this.unique(this.getTreeIds(this.AreaDataOld))
        let AreaDataList = this.unique(this.getTreeIds(this.AreaData))
        if (AreaDataOldList.length == AreaDataList.length) {
          let i = 0
          AreaDataOldList.forEach(item => {
            AreaDataList.forEach(item2 => {
              if (item == item2) {
                i++
              }
            })
          })
          if(i == AreaDataOldList.length){
            flag = true
          }else {
            flag = false
          }  
        }else {
          flag = false;
        }
        if(!flag){
          this.$Modal.fcWarning({
            title: '提示',
            mask: true,
            showCancel: true,
            content: '当前界面存在需要保存的数据，请确认是否保存？',
            onOk:()=>{
              this.saveAll();
              // this.getDeliveryRegion()
            },
            onCancel:()=> {
              this.getDeliveryRegion()
            }
          })
        }else {
          this.getDeliveryRegion()
        }
      },
      getProvinceList() {
        let params = {
          fixedcolumns: { regtype: ['=2'] }, 
          range: 2000, 
          startindex: 0, 
          table: 'T_OMSREGION' 
        };
        network.post('/p/cs/list/query', params).then((res) => {
          this.provinceList = res.data.rows.map(i=>({
            label: i.REGIONNAME.val,
            value: i.ID.val
          }));
        });
      },
      getLogisticsCompanyList() {
        this.logisticsCompanyList = [];
        let virtual={
          searchdata: {
            "table":"T_OMSLOGISTICSCOMPANY",
            "startindex":0,
            'range':3000,
            "fixedcolumns":{"ISACTIVE": "Y","NAME":this.logisticsCompanySearch},
            "column_include_uicontroller":true,
            "isolr":false
          }
        }
        network.post('/p/cs/QueryList', urlSearchParams(virtual)).then((res) => {
            res.data.data.row.forEach(item => {
              let obj = {
                logisticsCompanyName: item.NAME.val, // item.SHORTNAME.val
                id: item.ID.val
              };
              this.logisticsCompanyList.push(obj);
              if (!this.choosedLogisticsCompany) {
                this.choosedLogisticsCompany = this.logisticsCompanyList[0];
              }
              this.getDeliveryRegion();
            });
        })
      },
      getDeliveryRegion() {
        this.loading = true;
        this.AreaData = [];
        this.formAddArea.choosedProvinceList = [];
        network.get('/p/cs/delivery_region?logisticId='+this.choosedLogisticsCompany.id).then(res => {
          if(res.data.code == 0){
            let data = res.data.data;
            if(data){
              const { reachable_region_list, un_reachable_region_list } = data || {};
              let firstInfo = {};
              if (reachable_region_list && reachable_region_list.length) {
                firstInfo = reachable_region_list[0];
              }
              const { national } = firstInfo || {};
              this.nationalOld = national == 1 ? '0' : '1'; // 记录原始范围值
              if(reachable_region_list.length && national == 1){
                this.supportScope = '0';
                this.changeSupportScope(0,'load')
                let exclude_region_area_listArr = [];
                if(reachable_region_list.length > 0){
                  reachable_region_list.forEach(reachableRegion => {
                    const { items } = reachableRegion || {};
                    if (items && items.length) {
                      items.forEach(item => {
                        if(item.exclude_region_area_list){
                          let obj = {
                            region_id: item.region_id,
                            exclude_region_area_list: item.exclude_region_area_list
                          }
                          exclude_region_area_listArr.push(obj)
                        }
                      })
                    }
                  })
                }
                if(un_reachable_region_list && un_reachable_region_list.length > 0){
                    un_reachable_region_list.forEach(item => { // 一级国
                      if(item.items && item.items.length > 0){
                        item.items.forEach((itemOne,indexOne) => {  // 二级省
                          let obj = {
                            provinceId: itemOne.region_id,
                            province: itemOne.region_name,
                            excludedArea: '',
                            excludedSpecificArea: '',
                            modifiedBy: itemOne.modifiername?itemOne.modifiername:'',
                            modifiedTime: itemOne.modifieddate?itemOne.modifieddate:''
                          };
                          let sameData = this.AreaData.find(i=>i.provinceId == obj.provinceId);
                          if (!sameData) {
                            this.AreaData.push(obj);
                          }
                          let excludedArea = '';
                        if(itemOne.items && itemOne.items.length > 0){
                          let choosedCityAndAreaNew = []
                            itemOne.items.forEach((itemTwo, indexTwo) => { // 三级市
                              let obj = {
                                cityName: itemTwo.region_name,
                                cityId: itemTwo.region_id,
                                areaList: []
                              };
                              choosedCityAndAreaNew.push(obj);
                              this.choosedCityAndAreaArr.push(obj);
                              if(itemTwo.items && itemTwo.items.length > 0){
                                excludedArea += `${itemTwo.region_name}---`;
                              }else {
                                excludedArea += `${itemTwo.region_name}`;
                              }
                              if(itemTwo.items && itemTwo.items.length > 0){
                                itemTwo.items.forEach((itemThree, indexThree) => { // 四级区
                                  this.choosedCityAndAreaArr.forEach(choosedCity => {
                                    if(itemTwo.region_id == choosedCity.cityId){
                                      let obj = {
                                        PARENTID: itemTwo.region_id,
                                        checked: true,
                                        label: itemThree.region_name,
                                        value: itemThree.region_id,
                                      }
                                      choosedCity.areaList.push(obj)
                                    }
                                  })
                                  if (indexThree == itemTwo.items.length - 1) {
                                    excludedArea += itemThree.region_name;
                                  } else {
                                    excludedArea += `${itemThree.region_name}、`;
                                  }
                                });
                                if (indexTwo !== itemTwo.items.length - 1) {
                                  excludedArea += '；';
                                }
                              }
                            this.AreaData.forEach(itemArea => {
                              if(itemArea.provinceId == itemOne.region_id) {
                                itemArea.excludedArea = excludedArea
                                itemArea.modifiedTime = itemOne.modifieddate?itemOne.modifieddate:''
                                itemArea.modifiedBy = itemOne.modifiername?itemOne.modifiername:''
                                itemArea.excludedAreaList = choosedCityAndAreaNew
                              }
                              exclude_region_area_listArr.forEach(item => {
                                if(item.region_id == itemArea.provinceId){
                                  itemArea.excludedSpecificArea = item.exclude_region_area_list
                                }
                              })
                            })
                            this.totalArea = this.AreaData.length;
                            let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
                            let endIndex = startIndex + this.pageSizeArea;
                            this.currentAreaData = this.AreaData.slice(startIndex, endIndex);
                            })
                        }else {
                          this.totalArea = this.AreaData.length;
                          let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
                          let endIndex = startIndex + this.pageSizeArea;
                          this.currentAreaData = this.AreaData.slice(startIndex, endIndex);
                        }
                        })
                      }
                    })
                }else {
                  this.AreaData = [];
                  this.totalArea = this.AreaData.length;
                  let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
                  let endIndex = startIndex + this.pageSizeArea;
                  this.currentAreaData = this.AreaData.slice(startIndex, endIndex);
                }
              }else {
                this.supportScope = '1';
                this.changeSupportScope(1,'load')

                if(data.reachable_region_list && data.reachable_region_list.length > 0){
                  data.reachable_region_list.forEach(item => {// 自定义获取可送达的省
                    if(item.items && item.items.length > 0){
                      item.items.forEach(itemOne => {
                        this.formAddArea.choosedProvinceList.push(String(itemOne.region_id));
                        let obj = {
                          provinceId: itemOne.region_id,
                          province: itemOne.region_name,
                          excludedArea: '',
                          excludedSpecificArea: itemOne.exclude_region_area_list,
                          modifiedBy: itemOne.modifiername?itemOne.modifiername:'',
                          modifiedTime: itemOne.modifieddate?itemOne.modifieddate:''
                        };
                        let sameData = this.AreaData.find(i=>i.provinceId == obj.provinceId);
                        if (!sameData) {
                          this.AreaData.push(obj);
                        }
                        this.totalArea = this.AreaData.length;
                        let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
                        let endIndex = startIndex + this.pageSizeArea;
                        this.currentAreaData = this.AreaData.slice(startIndex, endIndex); // 当前页面显示明细
                      })
                    }
                  })
                  if(data.un_reachable_region_list && data.un_reachable_region_list.length > 0){ // 自定义获取可送达省排除的区域
                    data.un_reachable_region_list.forEach(item => { // 一级国
                      if(item.items && item.items.length > 0){
                        item.items.forEach((itemOne,indexOne) => {  // 二级省
                        let choosedCityAndAreaNew = []
                        let excludedArea = '';
                          if(itemOne.items && itemOne.items.length > 0){
                            itemOne.items.forEach((itemTwo, indexTwo) => { // 三级市
                            let obj = {
                              cityName: itemTwo.region_name,
                              cityId: itemTwo.region_id,
                              areaList: []
                            };
                            choosedCityAndAreaNew.push(obj);
                            this.choosedCityAndAreaArr.push(obj);
                             
                              if(itemTwo.items && itemTwo.items.length > 0){
                                excludedArea += `${itemTwo.region_name}---`;
                              }else {
                                excludedArea += `${itemTwo.region_name}`;
                              }
                              if(itemTwo.items && itemTwo.items.length > 0){
                                itemTwo.items.forEach((itemThree, indexThree) => { // 四级区
                                  this.choosedCityAndAreaArr.forEach(choosedCity => {
                                    if(itemTwo.region_id == choosedCity.cityId){
                                      let obj = {
                                        PARENTID: itemTwo.region_id,
                                        checked: true,
                                        label: itemThree.region_name,
                                        value: itemThree.region_id,
                                      }
                                      choosedCity.areaList.push(obj)
                                    }
                                  })
                                  if (indexThree == itemTwo.items.length - 1) {
                                    excludedArea += itemThree.region_name;
                                  } else {
                                    excludedArea += `${itemThree.region_name}、`;
                                  }
                                });
                                if (indexTwo !== itemTwo.items.length - 1) {
                                  excludedArea += '；';
                                }
                              }
                            this.AreaData.forEach(itemArea => {
                              if(itemArea.provinceId == itemOne.region_id) {
                                itemArea.excludedArea = excludedArea
                                itemArea.modifiedTime = itemOne.modifieddate?itemOne.modifieddate:''
                                itemArea.modifiedBy = itemOne.modifiername?itemOne.modifiername:''
                                itemArea.excludedAreaList = choosedCityAndAreaNew
                              }
                            })
                            })
                          }
                          this.totalArea = this.AreaData.length;
                          let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
                          let endIndex = startIndex + this.pageSizeArea;
                          this.currentAreaData = this.AreaData.slice(startIndex, endIndex);
                        })
                      }else {
                        this.totalArea = this.AreaData.length;
                        let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
                        let endIndex = startIndex + this.pageSizeArea;
                        this.currentAreaData = this.AreaData.slice(startIndex, endIndex);
                      }
                    })
                  }
                  this.formAddArea.choosedProvinceList = JSON.parse(JSON.stringify(this.formAddArea.choosedProvinceList))
                }else {
                  this.AreaData = [];
                  this.totalArea = this.AreaData.length;
                  let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
                  let endIndex = startIndex + this.pageSizeArea;
                  this.currentAreaData = this.AreaData.slice(startIndex, endIndex); // 当前页面显示明细
                }
              }
              this.AreaDataOld = JSON.parse(JSON.stringify(this.AreaData));
            }else {
              this.supportScope = '1';
              this.changeSupportScope(1,'load')
              this.nationalOld = '1'
              this.totalArea = this.AreaData.length;
              let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
              let endIndex = startIndex + this.pageSizeArea;
              this.currentAreaData = this.AreaData.slice(startIndex, endIndex); // 当前页面显示明细
            }
          }
          this.loading = false;
        })
      },
      companyClick(item) {
        // this.loading = true;
        this.AreaCurrentPage = 1;
        this.pageSizeArea = 10;
        this.choosedLogisticsCompany = item;
        this.submitArrArea = []
        this.getDeliveryRegion();
      },
      changeSupportScope(val,type) {
        if(!type){
          this.$Modal.fcWarning({
            title: '提示',
            mask: true,
            showCancel: true,
            content: '切换支持范围，已选择的区域信息将被清空，是否确认切换？',
            onOk:()=>{
              this.formAddArea.choosedProvinceList = [];
              this.formExcludedArea.choosedProvince = [];
              this.AreaData = [];
              this.totalArea = this.AreaData.length;
              let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
              let endIndex = startIndex + this.pageSizeArea;
              this.currentAreaData = this.AreaData.slice(startIndex, endIndex); // 当前页面显示明细
            },
            onCancel:()=>{
              this.isAllArea = !this.isAllArea;
              this.supportScope = this.supportScope == 0 ?'1':'0';
            }
          })
        }
        if (val == 1) {
          this.setAreaTitle = '配送以下地区';
          this.isAllArea = false;
          this.AreaColumns[2].title = '配送省份';
        } else {
          this.setAreaTitle = '排除以下地区';
          this.isAllArea = true;
          this.AreaColumns[2].title = '排除省份';
        }
      },

      // 区域页码改变时触发
      changePageArea(val) {
        // 1=>0 2=>10 3=>20 
        this.AreaCurrentPage = val;
        // 截取数组
        let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
        let endIndex = startIndex + this.pageSizeArea;
        this.currentAreaData = this.AreaData.slice(startIndex, endIndex);
      },
      // 区域页数改变时触发
      changeSizeArea(val) {
        this.pageSizeArea = val;
        this.AreaCurrentPage = 1;
        // this.currentAreaPage = 0;
        // 截取数组
        let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
        let endIndex = startIndex + this.pageSizeArea;
        this.currentAreaData = this.AreaData.slice(startIndex, endIndex);
      },
      // 区域表格选中某项时触发
      selectAreaData(selection, row) {
        this.submitArrArea = selection;
      },
      // 区域表格取消某项时触发
      selectAreaCancel(selection, row) {
        this.submitArrArea = selection;
      },
      // 区域表格全选
      selectAreaDataAll(selection) {
        this.submitArrArea = selection;
      },
      // 区域表格取消全选
      selectAreaDataCancel(selection) {
        this.submitArrArea = selection;
      },

      // 点击添加区域
      addArea() {
        this.addAreaModal = true;
      },
      changeAddArea(e) {
        // this.formAddArea.choosedProvinceList = e;
      },
      cancelAddArea() {
        this.addAreaModal = false;
      },
      okAddArea() {
        this.totalArea = [];
        this.provinceList.forEach(item => {
          this.formAddArea.choosedProvinceList.forEach(itemOne => {
            if (item.value == itemOne) {
              let obj = {
                provinceId: item.value,
                province: item.label,
                excludedArea: '',
                excludedSpecificArea: '',
                modifiedBy: JSON.parse(window.localStorage.getItem('userInfo')).userenv.$USER_TRUENAME$,
                modifiedTime: this.setModifiedTime()
              };
              // 去重
              let sameData = this.AreaData.find(i=>i.provinceId == obj.provinceId);
              if (!sameData) {
                this.AreaData.push(obj);
              }
              this.totalArea = this.AreaData.length;
              let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
              let endIndex = startIndex + this.pageSizeArea;
              this.currentAreaData = this.AreaData.slice(startIndex, endIndex); // 当前页面显示明细
            }
          });
        });
        this.cancelAddArea();
      },
      // 排除区域
      excludedArea() {
        console.log(this.isAllArea)
        console.log(this.submitArrArea)
        if (!this.isAllArea && this.submitArrArea.length == 0) {
          return this.$Message.warning('请选择需要操作的记录！');
        } if (this.submitArrArea.length > 1) {
          return this.$Message.warning('排除区域只能选择一条记录操作！');
        }
        if (this.submitArrArea.length == 1) {
          this.formExcludedArea.choosedProvince = String(this.submitArrArea[0].provinceId);
          this.excludedProvince = {
            label: this.submitArrArea[0].province,
            value: this.submitArrArea[0].provinceId
          };
          this.getCityList(this.submitArrArea[0].provinceId);
          this.excludedSpecificArea = this.submitArrArea[0].excludedSpecificArea;
        }else {
          this.formExcludedArea.choosedProvince = '';
          this.excludedProvince = {};
          this.excludedSpecificArea = '';
          this.excludedAreaList = [];
          this.cityList=[];
          this.areaList = [];
        }
        this.excludedAreaModal = true;
      },
      changeExcludedArea(e) {
        this.excludedProvince = e;
        this.getCityList(e.value);
      },
      // 根据省份查询市
      getCityList(val) {
        if (val != 0 && val != null && val) {
          // 市
          let virtual = {
            table: 'T_OMSREGION_CITY',
            isdroplistsearch: true,
            range: 1000,
            startindex: 0,
            fixedcolumns: { PARENTID: [`=${val}`] },
          };
          network.post('/p/cs/list/query', virtual).then((res) => {
            this.cityList = res.data.rows.map(i=>({
              label: i.REGIONNAME.val,
              value: i.ID.val,
              areaList: [], // 用于存储对应市下面的选择的区的数据
            }));
            if (this.submitArrArea.length == 1) {
              this.submitArrArea.forEach(item => {
                if (item.excludedAreaList && item.excludedAreaList.length) {
                  item.excludedAreaList.forEach(excludedArea => {
                    this.cityList.forEach(city => {
                      if (excludedArea.cityId == city.value) {
                        city.checked = true;
                        city.areaList = excludedArea.areaList;
                      }
                    });
                  });
                }
              });
            }else {
              this.AreaData.forEach(item => {
                if(item.provinceId == val){
                  if (item.excludedAreaList && item.excludedAreaList.length) {
                    item.excludedAreaList.forEach((excludedArea,index) => {
                      this.cityList.forEach((city,indexOne) => {
                        if (excludedArea.cityId == city.value) {
                          city.checked = true;
                          city.areaList = excludedArea.areaList;
                        }
                      });
                    });
                  }
                }
                this.areaList = [];
              });
            }
          });
        }
      },
      cityChange(item,index) {
        // this.chooseCity(item,index)
        this.getAreaList(item.value);
      },
      chooseCity(item, index) {
        this.getAreaList(item.value);
        this.cityList.forEach(itemOne => {
          itemOne.active = false;
        });
        this.cityList[index].active = true;
        this.cityList[index].checked = true;
        // this.cityList[index].areaList = [];
        this.cityList = JSON.parse(JSON.stringify(this.cityList));
      },
      // 根据市查询区
      getAreaList(val) {
        if (val != 0 && val != null && val) {
          // 市
          let virtual = {
            table: 'T_OMSREGION_AREA',
            isdroplistsearch: true,
            range: 1000,
            startindex: 0,
            fixedcolumns: { PARENTID: [`=${val}`] },
          };
          network.post('/p/cs/list/query', virtual).then((res) => {
            this.areaList = res.data.rows.map(i=>({
              label: i.REGIONNAME.val,
              value: i.ID.val,
              PARENTID: i.PARENTID.refobjid,
            }));
            this.cityList.forEach(item => {
              if (item.value == val) {
                if (item.areaList.length) {
                  item.areaList.forEach(area => {
                    this.areaList.forEach(areaOne => {
                      if (area.value == areaOne.value) {
                        areaOne.checked = true;
                      }
                    });
                  });
                }
              }
            });
          });
        }
      },
      chooseArea(item, index) {
        this.cityList.forEach((city,index) => {
          if (city.value == item.PARENTID) {
            if(item.checked){
              city.areaList.push(item);
            }else {
              // city.areaList.splice(index,1);
              city.areaList.forEach((Itemone,indexOne) => {
                if(Itemone.value == item.value){
                  city.areaList.splice(indexOne,1);
                }
              }) 
            }
          }
        });
      },
      cancelExcludedArea() {
        this.excludedAreaModal = false;
      },
      okExcludedArea() {
        this.choosedCityAndAreaArr = [];
        this.excludedAreaModal = false;
        this.cityList.forEach(city => {
          if (city.checked) {
            let obj = {
              cityName: city.label,
              cityId: city.value,
              areaList: city.areaList
            };
            
            this.choosedCityAndAreaArr.push(obj);
          }
        });
        if(this.excludedProvince.label && this.excludedProvince.label !== ''){
          this.addExcludedAreaToTable();
        }
      },
      addExcludedAreaToTable() {
        let excludedArea = '';
        this.choosedCityAndAreaArr.forEach((item, index) => {
          if(item.areaList && item.areaList.length > 0){
            excludedArea += `${item.cityName}---`;
          }else {
            excludedArea += `${item.cityName}`;
          }
          item.areaList.forEach((itemOne, indexOne) => {
            if (indexOne == item.areaList.length - 1) {
              excludedArea += itemOne.label;
            } else {
              excludedArea += `${itemOne.label}、`;
            }
          });
          if (index !== this.choosedCityAndAreaArr.length - 1) {
            excludedArea += '；';
          }
        });
        let obj = {
          provinceId: this.excludedProvince.value,
          province: this.excludedProvince.label,
          excludedArea,
          excludedAreaList: this.choosedCityAndAreaArr,
          excludedSpecificArea: this.excludedSpecificArea,
          modifiedBy: JSON.parse(window.localStorage.getItem('userInfo')).userenv.$USER_TRUENAME$,
          modifiedTime: this.setModifiedTime()
        };
        // 去重
        let sameData = this.AreaData.find(i=>i.provinceId == obj.provinceId);
        if (!sameData) {
          this.AreaData.push(obj);
        } else {
          this.AreaData.forEach(item=>{
            if (obj.provinceId == item.provinceId) {
              item = sameData;
              item.excludedArea = obj.excludedArea; // item.excludedArea ? `；${obj.excludedArea}` : obj.excludedArea
              item.excludedAreaList = obj.excludedAreaList; // [...item.excludedAreaList, ...obj.excludedAreaList]
              item.excludedSpecificArea = obj.excludedSpecificArea; // item.excludedSpecificArea ? `,${obj.excludedSpecificArea}` : obj.excludedSpecificArea; // 
            }
          });
        }
        this.totalArea = this.AreaData.length;
        let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
        let endIndex = startIndex + this.pageSizeArea;
        this.currentAreaData = this.AreaData.slice(startIndex, endIndex); // 当前页面显示明细

        // 清空弹框选择内容
        this.excludedProvince = '';
        this.formExcludedArea = {
          choosedProvince: '',
        };
        this.cityList = [];
        this.areaList = []; // 区数据
        this.choosedCityAndAreaArr = []; // 选中的市和区组合
        this.excludedSpecificArea = ''; // 排除具体区域
      },

      // 删除区域
      deleteArea() {
        let idArray = this.submitArrArea.map(item=>item.provinceId);
        this.AreaData = this.AreaData.filter(i =>!idArray.includes(i.provinceId));
        this.formAddArea.choosedProvinceList = this.formAddArea.choosedProvinceList.filter(i => !idArray.includes(i));
        this.totalArea = this.AreaData.length; // 总条数
        // 截取数组
        let startIndex = this.pageSizeArea * (this.AreaCurrentPage - 1);
        let endIndex = startIndex + this.pageSizeArea;
        this.currentAreaData = this.AreaData.slice(startIndex, endIndex); // 当前页面显示明细
      },
      // 修改时间
      setModifiedTime() {
        let date = new Date();
        let year = date.getFullYear().toString();
        let mouth = (date.getMonth() + 1) < 10 ? `0${(date.getMonth() + 1).toString()}` : (date.getMonth() + 1).toString();
        let day = date.getDate() < 10 ? `0${(date.getDate()).toString()}` : (date.getDate()).toString();
        let hh = date.getHours() < 10 ? `0${(date.getHours()).toString()}` : (date.getHours()).toString();
        let mm = date.getMinutes() < 10 ? `0${(date.getMinutes()).toString()}` : (date.getMinutes()).toString();
        let ss = date.getSeconds() < 10 ? `0${(date.getSeconds()).toString()}` : (date.getSeconds()).toString();
        let time = `${year}-${mouth}-${day} ${hh}:${mm}:${ss}`;
        return time;
      },
      saveAll() {
        let reachableRegionList = [];
        let unReachableRegionList = [];
        let exclude_region_street_list = [];
        if(this.supportScope == '0'){
          this.AreaData.forEach(item => {
            if(item.excludedSpecificArea) {
              let obj = {
                "regionId": item.provinceId,
                "exclude_region_area_list": item.excludedSpecificArea
              }
              exclude_region_street_list.push(obj)
            }
            if(item.excludedAreaList && item.excludedAreaList.length > 0){
              item.excludedAreaList.forEach(itemOne => {
                if(itemOne.areaList && itemOne.areaList.length > 0){
                  itemOne.areaList.forEach(itemTwo => {
                    unReachableRegionList.push(itemTwo.value)
                  })
                }else {
                  unReachableRegionList.push(itemOne.cityId)
                }
              })
            }else {
              unReachableRegionList.push(item.provinceId)
            }
          })
          reachableRegionList = ['1'];
        }else {
          this.AreaData.forEach(item => {
            reachableRegionList.push(item.provinceId)
            if(item.excludedSpecificArea) {
              let obj = {
                "regionId": item.provinceId,
                "exclude_region_area_list": item.excludedSpecificArea
              }
              exclude_region_street_list.push(obj)
            }
            if(item.excludedAreaList && item.excludedAreaList.length > 0){
              item.excludedAreaList.forEach(itemOne => {
                if(itemOne.areaList && itemOne.areaList.length > 0){
                  itemOne.areaList.forEach(itemTwo => {
                    unReachableRegionList.push(itemTwo.value)
                  })
                }else {
                  unReachableRegionList.push(itemOne.cityId)
                }
              })
            }
          })
        }
        let params = {
          logistic_id: this.choosedLogisticsCompany.id,
          national: this.supportScope == '0'?1:0,
          reachable_region_list: reachableRegionList,
          un_reachable_region_list: unReachableRegionList,
          exclude_region_street_list: exclude_region_street_list
        }
        this.loading = true;
        network.post('/p/cs/delivery_region',params).then(res => {
          if(res.data.code == 0){
            this.getDeliveryRegion();
            this.$Message.success('设置成功')
          }
          this.loading = false;
        })

      },
    },
  };
</script>
<style lang = 'less'>
  .setContentArea .foldPanelContent .ark-collapse > .ark-collapse-item > .ark-collapse-content {
    padding-top: 0px;
  }
  .choosedAreaProvince .ark-form {
    width: 100%;
  }
  .choosedAreaProvince .ark-select-multiple .ark-select-selection {
    min-height:32px;
  }
  .choosedAreaProvince .ark-select-multiple .ark-select-selection .ark-select-placeholder {
    line-height: 30px;
  }
  .choosedAreaProvince .ark-select-multiple .ark-select-item.ark-select-item-all {
    display: none;
  }
  .choosedAreaProvince .cityul .ark-checkbox-group-item {
    display: block;
  }
  .logisticsSearch .ark-input-wrapper {
    height: 100%;
  }
  .logisticsSearch .ark-input-wrapper .ark-input-with-suffix {
    height: 32px;
    line-height: 32px;
  }
  .logisticsSearch .ark-input-wrapper .ark-input-with-suffix {
    height: 32px;
    line-height: 32px;
  }
  .logisticsSearch .ark-input-wrapper .ark-input-prefix i, .logisticsSearch .ark-input-wrapper .ark-input-suffix i {
    line-height: 32px;
  }
</style>
<style lang='less' scoped>
  .SetLogisticsArea {
    display: flex;
    padding: 16px 0;
    height: 100%;
    .logisticsCompanyArea {
      width: 300px;
      background: #EEEEEE;
      padding: 16px 0px;
      margin-right: 16px;
      height: 100%;
      overflow-y: auto;
      .logisticsSearch {
        height: 32px;
        line-height: 32px;
        padding: 0 16px;
        margin-bottom: 8px;
      }
      .logisticsCompanyBox {
        .logisticsItem {
          height: 40px;
          line-height: 40px;
          font-size: 14px;
          padding: 0 16px;
          cursor: pointer;
          span {
            display: inline-block;
            width: 100%;
            color: #4c4c4c;
            padding-left: 8px;
            border-bottom: 1px solid #DDDDDD;
          }
        }
        .logisticsItem.itemactive {
          color: var(--primary-color);
          background: #fff;
        }
      }
    }
    .logisticsCompanySetArea {
      width: calc(100% - 300px);
      .quickOperation{
        height: 64px;
        display: flex;
        align-items: center;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
      }
      .quickOperation.quickOperationOne {
        border-bottom: 1px solid #D8D8D8;
        margin-bottom: 16px;
      }
      .choosedCompanyName {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 16px;
      }
      .setContentArea {
        .handleBtn{
          height:16px;
          margin-bottom:16px;
          display:flex;
          .handleItem{
            width: 48px;
            height: 16px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: var(--primary-color);
            line-height: 16px;
            margin: 0 2px;
            cursor: pointer;
          }
        } 
      }
    }
  }
  .choosedAreaProvince {
    display: flex;
    width: 100%;
    .afterProvince {
      display: flex;
      .cityul {
        max-height: 300px;
        overflow-y: auto;
        width: 40%;
        .cityItem {
          cursor: pointer;
        }
        .cityItem.cityActive {
          color: var(--primary-color);
        }
      }
      .areaul {
        max-height: 300px;
        overflow-y: auto;
        width: 50%;
        margin-left: 10px;
      }
    }
  }
  
  .pageContent {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
</style>
