<template>
  <div class="content_max" v-loading='pageLoading'>
    <!-- 配送服务类型 -->
    <div class="el_row_f1">
      <div class="el_Storage ">
        <span class="el_table_span">配送服务类型</span>
        <el-select
          class="el_Cselect"
          style="width: 100%;"
          v-model="form.dispatchServiceType"
          filterable
          placeholder="选择计费类型"
          @change="chargetype"
        >
          <el-option
            v-for="item in Warehousebillingmode"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <!-- 配送计费模式 -->
      <div class="el_select_check el_Storage ">
 
          <span class="el_table_span name">配送计费模式</span>
          <el-select
            v-model="form.dispatchPricingType"
            filterable
            placeholder="请选择配送计费模式"
            :popper-append-to-body="false"
            style="width:100%;"
            multiple
            @remove-tag="removeTag"
          >
            <el-option
              v-for="item in ServiceList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <el-checkbox v-model="item.check" @change="isChecked(item)">
                {{ item.label }}
              </el-checkbox>
            </el-option>
          </el-select>
  
      </div>
      <!-- 是否区分品类  -->
      <div  class="el_Storage" >
        <span class="el_table_span">是否区分品类</span>
        <el-radio-group
          @change="categoryChange"
          v-model="form.dispatchIsByCategory"
          class="el_Cselect el_fx"
          style="width: 100%"
        >
          <el-radio v-for="item in Distinguishcategories" :key="item.label" :label="item.value">{{
            item.label
          }}</el-radio>
        </el-radio-group>
      </div>

      <!-- 是否有遗留件  -->
      <div   class="el_Storage">
        <span class="el_table_span">是否有遗留件</span>
        <el-radio-group
          v-model="form.dispatchIsLeaveBehind"
          class="el_Cselect el_fx"
          style="width:100%"
        >
          <el-radio v-for="item in Leftoverparts" :key="item.label" :label="item.value">{{
            item.label
          }}</el-radio>
        </el-radio-group>
      </div>
    </div>
    <!-- 商配/市配  -->
    <div class="el_Storage" v-if="form.dispatchServiceType && form.dispatchIsByCategory">
      <el-tabs class="demo-tabs">
        <el-tab-pane
          :label="form.WarehousebillingmodeTitle"
          v-loading="Deliveryloading"
          element-loading-text="Loading..."
        >
          <!-- 商配/市配内容 -->
          <div class="el_Commercial_ercial" >
            <!-- 按件计费 -->
            <template v-for="Item in Commercialcial" :key="Item.title">
              <div v-if="Item.state" class="tabBox">
                <!-- 标题 -->
                <span class="el_table_span">{{ Item.title }}</span>
                <!-- 表格 -->
                <div
                  class="el_Storagecategory"
                  v-loading="Item.Storageloading"
                  element-loading-text="Loading..."
                >
                  <!-- 使用table标签创建表格 -->
                  <table class="styled-table">
                    <thead>
                      <tr>
                        <th style="width: 30px; text-align: center">序号</th>
                        <th>产品品类</th>
                        <th style="width: 104px">操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      <!-- 表格循环 -->
                      <tr v-for="item in Item.sequence" :key="item.id">
                        <!-- 序号 -->
                        <td style="text-align: center">{{ item.id }}</td>
                        <!-- 选择的品类 -->
                        <td>
                          <el-select
                            class="el_Cselect"
                            v-model="item.Warehousecategory"
                            filterable
                            remote
                            clearable
                            reserve-keyword
                            placeholder="请选择品类"
                            style="width: 100%"
                            remote-show-suffix
                            :remote-method="categoriesearch"
                            @focus="categoriesSearchfocus(item)"
                          >
                            <!-- 品类列表 -->
                            <el-option
                              v-for="option in item.Additionalcategories"
                              :key="option.value"
                              :label="option.label"
                              :value="option.value"
                            />
                          </el-select>
                        </td>
                        <td style="line-height: 16px">
                          <span
                            class="el_btn_a"
                            @click="storageplus(Item, item.id)"
                            v-if="item.plus"
                          >
                            <el-icon style="font-size: 12px; color: #409eff; margin-right: 3px"
                              ><CirclePlus /></el-icon
                            >新增
                          </span>
                          <span
                            class="el_btn_b"
                            @click="storagereduce(Item, item.id)"
                            v-if="item.reduce"
                          >
                            <el-icon style="font-size: 12px; color: #f00; margin-right: 3px"
                              ><Delete /></el-icon
                            >删除
                          </span>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 附加费计费 -->
    <div class="el_Commercial_ercial">
      <span class="el_title_span">附加费计费</span>
      <div class="el_fj">
        <!-- 是否有分货费  -->
        <div class="el_Storage">
          <span class="el_table_span">是否有分货费</span>
          <el-radio-group v-model="form.dispatchIsSortFee" class="el_Cselect">
            <el-radio v-for="item in Distributionfee" :key="item.label" :label="item.value">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </div>
        <!-- 是否有操作/装卸费  -->
        <div class="el_Storage">
          <span class="el_table_span">是否有操作/装卸费</span>
          <el-radio-group v-model="form.dispatchIsOperateFee" class="el_Cselect">
            <el-radio v-for="item in Operatingfee" :key="item.label" :label="item.value">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </div>

        <!-- 是否有上楼费  -->
        <div class="el_Storage">
          <div class="el_upstairs_a">
            <span class="el_table_span">是否有上楼费</span>
            <el-radio-group
              @change="UpstairsChange"
              v-model="form.dispatchIsStairsCarryingCharge"
              class="el_Cselect"
            >
              <el-radio v-for="item in upstairs" :key="item.label" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="el_Storage">
          <div class="el_upstairs_b" v-if="form.dispatchIsStairsCarryingCharge">
            <span class="el_table_span">是否配置免费层数</span>
            <el-radio-group v-model="form.dispatchIsFeeFloor" class="el_Cselect">
              <el-radio v-for="item in Numberlayers" :key="item.label" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
      <div class="el_translation">
        <!-- 是否有平移费  -->
        <div  class="el_Storage" >
          <span class="el_table_span">是否有平移费</span>
          <el-radio-group v-model="form.dispatchIsShiftingCharge" class="el_Cselect el_fx">
            <el-radio v-for="item in Translationfee" :key="item.label" :label="item.value">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </div>

        <!-- 附加费是否统一计费  -->
        <div class="el_Storage">
          <span class="el_table_span">附加费是否按品类计费</span>
          <el-radio-group v-model="form.dispatchIsCategorySubjoin" class="el_Cselect el_fx">
            <el-radio
              @change="SurchargeChange"
              v-for="item in Surchargefee"
              :key="item.label"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </div>

      </div>

      <!-- 附加费品类 -->
      <div class="el_Storage" v-if="form.dispatchIsCategorySubjoin">
        <div class="Storage-cont">
          <span class="el_table_span">附加费品类</span>
          <!-- 表格 -->
          <div
            class="el_Storagecategory"
            v-loading="goriesloading"
            element-loading-text="Loading..."
          >
            <!-- 使用table标签创建表格 -->
            <table class="styled-table">
              <thead>
                <tr>
                  <th style="width: 30px; text-align: center">序号</th>
                  <th>品类</th>
                  <th style="width: 104px">操作</th>
                </tr>
              </thead>
              <tbody>
                <!-- 表格循环 -->
                <tr v-for="item in AdditionalcategoriesList" :key="item.id">
                  <!-- 序号 -->
                  <td style="text-align: center">{{ item.id }}</td>
                  <!-- 选择的品类 -->
                  <td>
                    <el-select
                      class="el_Cselect"
                      v-model="item.Warehousecategory"
                      filterable
                      remote
                      clearable
                      reserve-keyword
                      placeholder="请选择品类"
                      style="width: 100%"
                      remote-show-suffix
                      :remote-method="categoriesearch"
                      @focus="categoriesSearchfocus(item)"
                    >
                      <!-- 品类列表 -->
                      <el-option
                        v-for="items in item.Additionalcategories"
                        :key="items.value"
                        :label="items.label"
                        :value="items.value"
                      />
                    </el-select>
                  </td>
                  <td style="line-height: 16px">
                    <span @click="categoriesplus(item.id)" v-if="item.plus" class="el_btn_a">
                      <el-icon style="font-size: 12px; color: #409eff; margin-right: 3px"
                        ><CirclePlus /></el-icon
                      >新增
                    </span>
                    <span @click="categoriesduce(item.id)" v-if="item.reduce" class="el_btn_b">
                      <el-icon style="font-size: 12px; color: #f00; margin-right: 3px"
                        ><Delete /></el-icon
                      >删除
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- 最低计费  -->
      <div class="el_Storage el_Minimumbilling">
        <span>最低计费</span>
        <div class="el_Storage">
          <div class="el_Minimumbillingbox">
            <!-- 是否最低计费 -->
            <div class="el_flex_row"  >
              <span class="el_table_span">是否最低计费</span>
              <el-radio-group v-model="form.dispatchIsMinCost" class="el_Cselect el_fx">
                <el-radio
                  @change="MinimumChange"
                  v-for="item in Minimumbilling"
                  :key="item.label"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </div>
            <!-- 最低计费方式 -->
            <!-- v-if="form.dispatchIsMinCost" -->
            <div
            v-if="form.dispatchIsMinCost" class="el_flex_row" >
              <span class="el_table_span">最低计费方式</span>
              <el-radio-group v-model="form.dispatchMinCostMode" class="el_Cselect el_fx">
                <el-radio v-for="item in Billingmethod" :key="item.label" :label="item.value">{{
                  item.label
                }}</el-radio>
              </el-radio-group>
            </div>
            <!-- 最低计费类型  -->

            <div class="el_flex_row"  v-if="form.dispatchIsMinCost">
              <span class="el_table_span">最低计费类型</span>
              <el-radio-group v-model="form.dispatchMinCostType" class="el_Cselect el_fx">
                <el-radio v-for="item in chargetypeSelect" :key="item.label" :label="item.value">{{
                  item.label
                }}</el-radio>
              </el-radio-group>
            </div>

            <!-- 是否向上判断  -->
     
            <div  v-if="!form.dispatchIsMinCost" class="el_flex_row" >
              <span class="el_table_span">是否向上判断</span>
              <el-radio-group v-model="form.dispatchIsUpwardJudgment" class="el_Cselect el_fx">
                <el-radio v-for="item in Upwardjudgment" :key="item.label" :label="item.value">{{
                  item.label
                }}</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 操作按钮 -->
    <div class="flex-c-c">
      <el-button type="primary" icon="Refresh" @click="resetFormData">重置</el-button>
      <el-button type="primary" icon="Position" @click="handleSubmit">保存</el-button>
    </div>

    
  </div>
</template>

<script setup>
import { ref, defineEmits, defineComponent } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import { getDictionaryBiz } from '@/api/system/dict'; //字典
import { deepClone } from '@/utils/util';
import { postFindCategoryInfo } from '@/api/distribution/CreateOrder.js';
import { $_priceTemplate, $_putpriceTemplate } from '@/api/financialsector/index'; //价格模板
const $route = useRoute(); //获取地址栏参数
const emit = defineEmits(['request-data']);
defineComponent({
  emits: ['request-data'],
});
// 接收参数
const props = defineProps({
  templateData: Object,
});
console.log(props, '来自父页面参数');
//表单
const pageLoading=ref(false)
const formCopy = ref(null); //拷贝的数据
const form = ref({
  dispatchServiceType: '', //仓储计费类型
  dispatchIsByCategory: 0, //是否区分品类
  dispatchIsLeaveBehind: 0, //是否有遗留件
  dispatchIsSortFee: 0, //是否有分货费
  dispatchIsOperateFee: 0, //是否有操作装卸费
  dispatchIsStairsCarryingCharge: 0, //是否有上楼费
  dispatchIsFeeFloor: null, //是否配置免费层数
  dispatchIsShiftingCharge: 0, //是否有平移费
  dispatchIsCategorySubjoin: 0, //附加费
  dispatchIsMinCost: 0, //是否最低计费
  dispatchMinCostMode: null, //最低计费方式
  dispatchMinCostType: 1, //最低计费类型
  dispatchIsUpwardJudgment: 0, //是否向上判断
  WarehousebillingmodeTitle:'',//标题
});
const SelectOpin = ref(null); //当前点击的品类搜索框
// 是否向上判断
const Upwardjudgment = ref([]);
const CommercialcialCopy=ref([]);//服务类型拷贝
// 最低计费类型
const chargetypeSelect = ref([]);
// 最低计费方式
const Billingmethod = ref([]);
// 是否显示服务类型选择的列表
const StateDelivery = ref(false);
// 是否最低计费
const Minimumbilling = ref([]);
// 附加品类loading
const goriesloading = ref(false);
// 附加费加载
const SurchargeState = ref(false);
// 上楼费是否展示配置
const UpstairsState = ref(false);
// 是否品类填写
const categoriesState = ref(false);
// 附加费品类配置
const AdditionalcategoriesList = ref([
  {
    id: 1,
    plus: true,
    reduce: false,
    StateName: 'additional', //附加费标识
    Warehousecategory: '', //选择框值
    Additionalcategories: [],
  },
]);
// 附加费是否统一计费
const Surchargefee = ref([]);
//是否有平移费
const Translationfee = ref([]);
//是否配置免费层数
const Numberlayers = ref([]);
// 是否有上楼费
const upstairs = ref([]);
// 是否最低计费展示
const MinimumState = ref(false);
//是否有分货费
const Distributionfee = ref([]);
//是否有操作装卸费
const Operatingfee = ref([]);
const Deliveryloading = ref(false);
// 配送服务类型
const Warehousebillingmode = ref([]);
const WarehousebillingmodeTitle = ref(''); //配送服务类型标题
// 配送计费模式
const ServiceList = ref([]);
const Commercialcial = ref([]);
// 是否区分品类
const Distinguishcategories = ref([]);
// 是否有遗留件
const Leftoverparts = ref([]);
// 计费类型选择
const chargetype = val => {
  console.log(val);
  if (val) {
    form.value.WarehousebillingmodeTitle = Warehousebillingmode.value.find(
      res => res.value == val
    ).label;
  }
};
//案件计费
const Storageloading = ref(false);
// 附加费品类
const Additionalcategories = ref([
  {
    label: '衣柜',
    value: '1',
  },
  {
    label: '橱柜',
    value: '2',
  },
]);

const Timedelive = () => {
  Deliveryloading.value = true;
  let timerId = setTimeout(() => {
    Deliveryloading.value = false;
    clearTimeout(timerId); // 在回调函数内部清除定时器
  }, 300);
};

// 根据当前选择的服务类型来选择是否显示框框
const CommercialcialDisplay = () => {
  if (Commercialcial.value.find(res => res.state)) {
    StateDelivery.value = true;
  } else {
    StateDelivery.value = false;
  }
};
// 是否面配置楼层
const UpstairsChange = val => {
  if (val == 1) {
    form.value.dispatchIsFeeFloor = 0; //初始化参数
  } else {
    form.value.dispatchIsFeeFloor = null; //初始化参数
  }
};
// 是否区分品类
const categoryChange = val => {
  if (val == 1) {
    categoriesState.value = true;
  } else {
    categoriesState.value = false;
  }
};
// 是否最低计费展示
const MinimumChange = val => {
  console.log(val);
  if (val) {
    form.value.dispatchMinCostMode = 1;
    form.value.dispatchIsUpwardJudgment = null; //向上判断
  } else {
    form.value.dispatchMinCostMode = null;
    form.value.dispatchIsUpwardJudgment = 0; //向上判断
  }
};
// 点击菜单
const isChecked = value => {
  if (!form.value.WarehousebillingmodeTitle) {
    ElMessage({
      message: '请先选择仓储计费类型',
      type: 'warning',
    });
    form.value.dispatchPricingType = []; //清空选择

    value.check = false; //取消当前勾选
    return;
  }
  console.log(value, '当前点击的菜单');
  //   找到当前点击的菜单,显示对应的列表
  if (value.value == '1' || value.value == '2' || value.value == '3') {
    let data = ServiceList.value.find(res => res.label == value.label);
    console.log(data,'data===>');
    console.log( Commercialcial.value,'要处理的数据');
    Commercialcial.value.find(res => res.title == data.label).state = !Commercialcial.value.find(
      res => res.title == data.label
    ).state;
  }

  CommercialcialDisplay(); // 根据当前选择的服务类型来选择是否显示框框
  Timedelive(); //加载效果
};
// 点击移除
const removeTag = value => {
  Deliveryloading.value = true;
  let data = ServiceList.value.find(res => res.value == value);
  data.check = false;
  Commercialcial.value.find(res => res.title == data.label).state = false;
  // 根据当前选择的服务类型来选择是否显示框框
  CommercialcialDisplay(); // 根据当前选择的服务类型来选择是否显示框框
  Timedelive(); //加载效果
};

// 移除对象
function removeItemById(array, id) {
  const index = array.sequence.findIndex(item => item.id === id);
  if (index !== -1) {
    array.sequence.splice(index, 1);
    array.sequence.forEach((item, index) => {
      item.id = index + 1;
    });
  }
  let timerId = setTimeout(() => {
    array.Storageloading = false;
    clearTimeout(timerId); // 在回调函数内部清除定时器
  }, 300);
}
// 添加对象

function addItemAfterId(array, id) {
  console.log(array, 'array');
  const newItem = {
    id: array.sequence.length + 1, // 新对象的 ID 为当前数组长度加 1
    plus: true, //加号
    reduce: true, //减号
    StateName: 'storage', //仓储标识
    Additionalcategories: [], //品类
    Warehousecategory: '', //选择的值
  };

  const index = array.sequence.findIndex(item => item.id === id);
  if (index !== -1) {
    array.sequence.splice(index + 1, 0, newItem); // 在找到的 ID 后面插入新对象
    // 重新排序 ID
    array.sequence.forEach((item, index) => {
      item.id = index + 1;
    });
  }
  let timerId = setTimeout(() => {
    array.Storageloading = false;
    clearTimeout(timerId); // 在回调函数内部清除定时器
  }, 300);

  // 取消定时器
}
// 仓储减
const storagereduce = (item, id) => {
  console.log(item);
  item.Storageloading = true;
  removeItemById(item, id);
};
// 仓储加
const storageplus = (item, id) => {
  console.log(item, '按钮接收参数');
  item.Storageloading = true;
  addItemAfterId(item, id);
  console.log(Commercialcial.value, 'Commercialcial');
};
// 附加品类加移除对象
function FmremoveItemById(array, id) {
  const index = array.findIndex(item => item.id === id);
  if (index !== -1) {
    array.splice(index, 1);
    array.forEach((item, index) => {
      item.id = index + 1;
    });
  }
  let timerId = setTimeout(() => {
    goriesloading.value = false;
    clearTimeout(timerId); // 在回调函数内部清除定时器
  }, 300);
}

// 附加品类加添加对象
function FmaddItemAfterId(array, id) {
  console.log(array);
  const newItem = {
    id: array.length + 1, // 新对象的 ID 为当前数组长度加 1
    plus: true, //是否显示加号
    StateName: 'additional', //附加费标识
    reduce: true, //是否显示减号
    Warehousecategory: '', //选择框值
    Additionalcategories: [], //选择框列表,防止后期需要改动列表值
  };
  const index = array.findIndex(item => item.id === id);
  if (index !== -1) {
    array.splice(index + 1, 0, newItem); // 在找到的 ID 后面插入新对象
    // 重新排序 ID
    array.forEach((item, index) => {
      item.id = index + 1;
    });
  }
  let timerId = setTimeout(() => {
    goriesloading.value = false; //关闭加载效果
    clearTimeout(timerId); // 在回调函数内部清除定时器
  }, 300);
  // 取消定时器
}
// 附加品类加
const categoriesplus = id => {
  goriesloading.value = true;
  FmaddItemAfterId(AdditionalcategoriesList.value, id);
};
// 附加品类减
const categoriesduce = id => {
  goriesloading.value = true;
  FmremoveItemById(AdditionalcategoriesList.value, id);
};

function updateDictionary(targetArray, dictionaryType) {
  getDictionaryBiz(dictionaryType)
    .then(async res => {
      console.log(res, '字典');
      if (res.data.code == 200) {
        if (res.data.data.length) {
          res.data.data.forEach(item => {
            targetArray.push({
              value: Number(item.dictKey),
              label: item.dictValue,
              id: item.id,
            });
          });
        }
      }

      //服务类型
      if (dictionaryType == 'dispatch_pricing_type') {
        Commercialcial.value = []; //清空服务类型
        res.data.data.forEach(res => {
          let data = {
            title: res.dictValue, // 标题
            id: Number(res.dictKey), //码表ID
            state: false, //是否显示
            Storageloading: false, //加载效果
            sequence: [
              //表格
              {
                id: 1, //序号
                plus: true, //加号显示
                reduce: false, //减号显示
                Additionalcategories: [], //品类
                Warehousecategory: '', //选择的值
                StateName: 'storage', //附加费标识
              },
            ],
          };
          Commercialcial.value.push({
            ...data,
          });
          
        });
        CommercialcialCopy.value=deepClone(Commercialcial.value)
  
      }
      console.log(form.value, '服务类型');
      // 是否类型
      if (dictionaryType == 'price_yes_no') {
        Leftoverparts.value = { ...Distinguishcategories.value }; //是否有遗留件
        Distributionfee.value = { ...Distinguishcategories.value }; //是否有分货费
        Operatingfee.value = { ...Distinguishcategories.value }; //是否有操作/装卸费
        upstairs.value = { ...Distinguishcategories.value }; //是否有上楼费
        Numberlayers.value = { ...Distinguishcategories.value }; //是否配置免费层数
        Translationfee.value = { ...Distinguishcategories.value }; //是否有平移费
        Surchargefee.value = { ...Distinguishcategories.value }; //附加费是否统一计费
        Minimumbilling.value = { ...Distinguishcategories.value }; //是否最低计费
        Upwardjudgment.value = { ...Distinguishcategories.value }; //是否向上判断
      }

      // 编辑回显
      if (props.templateData.request) {
        let request = props.templateData.request;
        form.value = await deepClone(request);

        form.value.dispatchPricingType = request.dispatchPricingType
          ? request.dispatchPricingType.split(',').map(Number)
          : []; //服务类型

        ServiceList.value.forEach(dataItem => {
          if (form.value.dispatchPricingType.includes(dataItem.value)) {
            dataItem.check = true;
          }
        });

        if (request.dispatchIsByCategory) {
          categoriesState.value = true; //区分品类
          console.log(categoriesState.value, '是否区分品类');
        }
        // 配送服务类型标题
        form.value.WarehousebillingmodeTitle = Warehousebillingmode.value.find(
          res => res.value == form.value.dispatchServiceType
        ).label;
        StateDelivery.value = true; //显示表格
        // 显示那些表格
        Commercialcial.value.forEach(dataItem => {
          // 检查当前dataItem的id是否为1, 2, 或 3 且 dispatchPricingType数组包含这个id
          if (
            [1, 2, 3].includes(dataItem.id) &&
            form.value.dispatchPricingType.includes(dataItem.id)
          ) {
            dataItem.state = true;
          } else {
            // 如果需要，这里可以添加处理其他情况的逻辑，默认情况下不设置state或设置为false
            // 例如 dataItem.state = false;
          }
        });
        // 按件计费回显
        if (request.dispatchPieceCategory) {
          let piece = Commercialcial.value.find(res => res.id == 1);
          piece.sequence = [];
          request.dispatchPieceCategorys.forEach((res, index) => {
            console.log(piece, '按件显示');
            piece.sequence.push({
              Additionalcategories: [
                {
                  label: res.name,
                  value: res.id,
                },
              ],
              StateName: 'storage',
              Warehousecategory: res.id,
              id: index + 1,
              plus: true,
              reduce: !index ? false : true,
            });
          });
        }
        // 按重量
        if (request.dispatchWeightCategory) {
          let piece = Commercialcial.value.find(res => res.id == 2);
          piece.sequence = [];
          request.dispatchWeightCategorys.forEach((res, index) => {
            console.log(piece, '按件显示');
            piece.sequence.push({
              Additionalcategories: [
                {
                  label: res.name,
                  value: res.id,
                },
              ],
              StateName: 'storage',
              Warehousecategory: res.id,
              id: index + 1,
              plus: true,
              reduce: !index ? false : true,
            });
          });
        }
        // 按方
        if (request.dispatchCubeCategory) {
          let piece = Commercialcial.value.find(res => res.id == 3);
          piece.sequence = [];
          request.dispatchCubeCategorys.forEach((res, index) => {
            console.log(piece, '按件显示');
            piece.sequence.push({
              Additionalcategories: [
                {
                  label: res.name,
                  value: res.id,
                },
              ],
              StateName: 'storage',
              Warehousecategory: res.id,
              id: index + 1,
              plus: true,
              reduce: !index ? false : true,
            });
          });
        }

        // 附加品类回显
        if (request.dispatchSubjoinCategory) {
          AdditionalcategoriesList.value = [];
          console.log('执行1');
          request.dispatchSubjoinCategorys.forEach((res, index) => {
            console.log('执行2');
            AdditionalcategoriesList.value.push({
              Additionalcategories: [
                {
                  label: res.name,
                  value: res.id,
                },
              ],
              StateName: 'additional',
              Warehousecategory: res.id,
              id: index + 1,
              plus: true,
              reduce: !index ? false : true,
            });
          });
        }

        //       function updateSequence(requestCategorys, commercialId, stateName) {
        //   let piece = Commercialcial.value.find(res => res.id == commercialId);
        //   if (!piece) return; // 确保找到了相应的部分再继续

        //   piece.sequence = []; // 重置sequence防止数据累加
        //   requestCategorys.forEach((res, index) => {
        //     piece.sequence.push({
        //       Additionalcategories: [{
        //         label: res.name,
        //         value: res.id,
        //       }],
        //       StateName: stateName,
        //       Warehousecategory: res.id,
        //       id: index + 1,
        //       plus: true,
        //       reduce: !index ? false : true,
        //     });
        //     console.log(piece, `按${stateName}显示`); // 根据状态显示不同的日志
        //   });
        // }

        // // 按件计费回显
        // if (request.dispatchPieceCategory) {
        //   updateSequence(request.dispatchPieceCategorys, 1, "storage");
        // }

        // // 按重量
        // if (request.dispatchWeightCategory) {
        //   updateSequence(request.dispatchWeightCategorys, 2, "storage");
        // }

        // // 按方
        // if (request.dispatchCubeCategory) {
        //   updateSequence(request.dispatchCubeCategorys, 3, "storage");
        // }

        // // 附加品类回显
        // if (request.dispatchSubjoinCategory) {
        //   AdditionalcategoriesList.value = []; // 重置数组
        //   updateSequence(request.dispatchSubjoinCategorys, 0, "additional");
        // }
      }
    })
    .catch(() => {})
    .finally(() => {});
}

const categoriesSearchfocus = item => {
  console.log(item, 'item');
  SelectOpin.value = item; //获取当前点击的是那个品类输入框
};
// 附加费是否按品类计费
const SurchargeChange = val => {
  if (val) {
    AdditionalcategoriesList.value = [
      {
        id: 1,
        plus: true,
        reduce: false,
        StateName: 'additional', //附加费标识
        Warehousecategory: '', //选择框值
        Additionalcategories: [],
      },
    ];
  }
};
// 附加品类的搜索
const categoriesearch = goodsName => {
  console.log(goodsName, '当前搜索参数');
  if (!goodsName) {
    return;
  }
  let data = {
    goodsName: goodsName,
  };

  console.log(SelectOpin.value, '当前点击的谁');
  postFindCategoryInfo(data).then(res => {
    console.log(res, '附加费品类计费');
    if (res.data.code == 200) {
      if (res.data.data.length) {
        SelectOpin.value.Additionalcategories = []; //如果有新的参数就清空之前的
        res.data.data.forEach(item => {
          SelectOpin.value.Additionalcategories.push({
            label: item.goodsName,
            value: item.goodsId,
          });
        });
      }
    }
  });
};
const clink=()=>{
  if(ServiceList.value.length)
  ServiceList.value.forEach(res=>res.check=false)
}
/** 重置数据 */
const resetFormData = () => {
    console.log( CommercialcialCopy.value);
  ElMessageBox.confirm('是否重置数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
   pageLoading.value = true;
   clink()
   Commercialcial.value = deepClone(CommercialcialCopy.value) 
  form.value = deepClone(formCopy.value);
    setTimeout(() => {
  pageLoading.value = false;
    }, 300);
  });
};


// 页面初始化必要请求
const onLoad = async() => {
 await updateDictionary(ServiceList.value, 'dispatch_pricing_type'); //仓储计费类型
  formCopy.value =await deepClone(form.value);
  updateDictionary(Warehousebillingmode.value, 'dispatch_type'); //仓储计费类型
  updateDictionary(Distinguishcategories.value, 'price_yes_no'); //是否区分品类
  updateDictionary(Billingmethod.value, 'min_cost_way'); //是否区分品类
  updateDictionary(chargetypeSelect.value, 'min_cost_type'); //最低计费类型
};
onLoad();
// 保存事件
const handleSubmit = async () => {
  await emit('request-data'); //通知父页面传递数据
  console.log(props, 'props');

  if (!props.templateData.TemplateName) {
    ElMessage({
      message: '请输入模板名称',
      type: 'warning',
    });
    return;
  } else {
    form.value.name = props.templateData.TemplateName; //模板名称
  }
  if (!props.templateData.brand) {
    ElMessage({
      message: '请选择品牌',
      type: 'warning',
    });
    return;
  } else {
    form.value.brandId = props.templateData.brand; //品牌ID
  }

  if (!form.value.dispatchServiceType) {
    ElMessage({
      message: '请选择配送服务类型',
      type: 'warning',
    });
    return;
  }
  if (!form.value.dispatchPricingType.length) {
    ElMessage({
      message: '请选择配送计费模式',
      type: 'warning',
    });
    return;
  }

  form.value.serviceType = props.templateData.ServiceType.join(','); //顶部选择的服务类型
  console.log(form.value, '初始表单');
  console.log(Commercialcial.value, 'Commercialcial');
  // 初始化数据
  const Submit = deepClone(form.value); //拷贝一份要提交的数据

  console.log(Commercialcial.value, '服务类型');
  Submit.dispatchPricingType = Submit.dispatchPricingType.join(','); //服务类型处理
  console.log(AdditionalcategoriesList.value, '附加费品类');

  // 处理服务类型
  function checkAndProcessServiceType(serviceTypeId, message, submitField) {
    const item = Commercialcial.value.find(res => res.id == serviceTypeId);
    if (item.sequence.find(res => !res.Warehousecategory)) {
      ElMessage({
        message,
        type: 'warning',
      });
      return true; // 表示检查未通过
    }
    Submit[submitField] = item.sequence.map(res => res.Warehousecategory).join(','); // 根据类型处理
    console.log(Submit[submitField], '123');
    return false; // 表示检查已通过
  }
  // 选择了是否区分品类才进行处理数据
  console.log(categoriesState.value, 'categoriesState.value');
  if (form.value.dispatchIsByCategory){
    if(!form.value.dispatchPricingType.find(res=>res.value ==1)){
         Submit.dispatchPieceCategory=''
      }
      if(!form.value.dispatchPricingType.find(res=>res.value ==2)){
         Submit.dispatchWeightCategory=''
      }
      if(!form.value.dispatchPricingType.find(res=>res.value ==3)){
         Submit.dispatchCubeCategory=''
      }



    for (const res of form.value.dispatchPricingType) {
      let shouldReturn = false;
      switch (res) {
        case 1:
          shouldReturn = checkAndProcessServiceType(
            1,
            '请填写完整按件处理',
            'dispatchPieceCategory'
          );
          break;
        case 2:
          shouldReturn = checkAndProcessServiceType(
            2,
            '请填写完整按重量处理',
            'dispatchWeightCategory'
          );
          break;
        case 3:
          shouldReturn = checkAndProcessServiceType(
            3,
            '请填写完整按方处理',
            'dispatchCubeCategory'
          );
          break;
        default:
          break;
      }
      if (shouldReturn) return; // 如果检查未通过，退出当前函数
    }
  }else{
   Submit.dispatchPieceCategory=''
   Submit.dispatchWeightCategory=''
   Submit.dispatchCubeCategory=''
  }


  



  // 附加费是否按品类计费选择了是才进行处理
  if (form.value.dispatchIsCategorySubjoin) {
    Submit.dispatchSubjoinCategory = AdditionalcategoriesList.value
      .map(res => res.Warehousecategory)
      .join(','); //附加费品类
  }else{
    if(Submit.dispatchSubjoinCategory){
     Submit.dispatchSubjoinCategory=''
    }
  }

  console.log(Submit, '要提交的数据');
  if (props.templateData.code || $route.query.id) {
    console.log('走编辑接口');
    // 编辑接口
    let data = {
      id: props.templateData.code, //模板ID
      ...Submit,
      checkType: 4, //服务类型
    };
    $_putpriceTemplate(data).then(res => {
      console.log(res, '提交成功后返回值');
      if (res.data.code == 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
        });
      }
    });
  } else {
    // 新增接口
    let data = {
      ...Submit,
    };
    console.log('走新增接口');
    $_priceTemplate(data).then(res => {
      console.log(res, '提交成功后返回值');
      if (res.data.code == 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
        });
        emit('request-data', res.data.data); //把获取到的数据传递给父页面
      }
    });
  }
};
</script>

<style scoped lang="scss">
.content_max {
  padding: 10px;
}

.el_Service {
  display: flex;
  align-items: center;
  .name {
    margin-right: 10px;
  }
  .el-checkbox {
    width: 100% !important;
    padding: 0 30px;
    .el-checkbox__label {
      width: 100%;
      margin-left: 20px;
    }
  }

  .name {
    font-size: 16px;
  }
}

.el-checkbox {
  width: 100% !important;
  padding-left: 10px;
  box-sizing: border-box;
  .el-checkbox__label {
    margin-left: 20px;
  }
}

.el-select-dropdown__item {
  padding: 0;
}
.el-select-dropdown__item::after {
  content: '';
  display: none;
}
.el_Storage {
  margin-bottom: 30px;
  .el_Cselect {
  }
  .el_table_span {
    font-size: 16px;
    font-weight: 500;
    display: inline-block;
    width: 160px;
    margin-bottom: 10px;
    height: 16px;
  }
  .Storage-cont {
    /* 禁止双击选中文本 */
    -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE 10+/Edge */
    user-select: none; /* Standard syntax */
    display: flex;
    flex-direction: column;
    width: 390px;
    .el_Storagecategory {
      .el_table_span {
        display: flex;
        width: 100%;
        background-color: #ebeef5;
        border-bottom: 1px solid #ccc;
        box-sizing: border-box;
        // justify-content: space-between;
        justify-content: space-around;
      }
      .el_table_border {
        height: 30px;
        margin-bottom: 0;
        align-items: center;
      }
      .el_table_id {
        width: 14%;
        color: #606266;
        // border-right: 1px solid #ccc;
        font-weight: 500;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
      }
      .el_table_title {
        font-weight: 600;
        color: #606266;
        font-weight: 500;
        display: flex;
        width: 55%;
        height: 100%;
        justify-content: center;
        align-items: center;
        position: relative;
      }
      .el_table_title::before {
        content: '';
        width: 0.5px;
        height: 100%;
        background-color: #ccc;
        position: absolute;
        right: 0;
        top: 0;
      }
      .el_table_id::before {
        content: '';
        width: 0.5px;
        height: 100%;
        background-color: #ccc;
        position: absolute;
        right: 0;
        top: 0;
      }
      .el_table_operation {
        color: #606266;
        display: flex;
        font-weight: 500;
        height: 100%;
        width: 30%;
        align-items: center;
        justify-content: center;
        span {
          padding-left: 3px;
        }
      }
      .el_table_td {
        display: flex;
        height: 40px;
        align-items: center;
        border-bottom: 1px solid #ccc;
        position: relative;
        .el_table_operation {
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: space-between;
          position: absolute;
          right: 0px;
          border-left: 1px solid #ccc;
          padding: 0 3px;
          width: 110px;
          .el_table_operation_span_a,
          .el_table_operation_span_b {
            font-size: 14px;
            color: #f00;
            height: 70%;
            border-radius: 6px;
            display: block;
            text-align: center;
            cursor: pointer;
            display: flex;
            align-items: center;
          }
          .el_table_operation_span_b {
            color: #0d83b7;
          }

          // .el_table_operation_span_a:hover {
          //   background-color: #f00;
          //   color: #ccc;
          // }
          // .el_table_operation_span_b:hover {
          //   background-color: #0d83b7;
          //   color: #ccc;
          // }
        }
      }
      .el_table_idNumber {
        width: 14%;
        text-align: center;
        font-size: 16px;
        font-weight: 400;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        border-right: 1px solid #ccc;
      }
      :deep(.el-input__wrapper) {
        box-shadow: none;
      }
    }
  }
}

:deep(.demo-tabs) {
  .el-tabs__item {
    font-size: 26px;
    font-weight: bold;
  }

  .el_Commercial_ercial {
    width: 100%;
    max-height: 500px;
    box-sizing: border-box;
    border-radius: 4px;
    display: flex;
    overflow-y: scroll;
    .el_margin {
      margin-left: 20px;
    }
    .el_margin:first-child {
      margin-left: 0;
    }
  }
}
.el_Surchargebilling {
  .el_title_span {
    font-weight: bold;
  }
}

.el_upstairs {
  display: flex;
  .el_upstairs_b {
    margin-left: 70px;
  }
}
.el_Minimumbilling {
  .el_Minimumbillingbox {
    display: flex;
    .el_flex_row{
      display: flex;
      flex-direction: column;
      width: 24%;
      margin-right: 30px;
      .el-radio-group{
        width: 100%;
      }
    }
  }

}
.el_flex {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  .el_Cselect {
    margin-left: 0;
  }
}
:deep(.el_row_f1) {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  .el-select {
  }
  .el_Storage {
    width: 24%;
  }
  .el-select__tags {
    width: 100%;
  }
}
.el_fx {
  background-color: #f6f6f6;
  padding: 0 6px;
  border-radius: 4px;
}
.el_fj {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
  .el_Storage {
    display: flex;
    flex-direction: column;
    width: 24%;
    .el_Cselect {
      background-color: #f6f6f6;
      width: 100%;
      padding: 0 4px;
    }
  }
}
.el_table_select {
  width: 55%;
  display: flex;
  align-items: center;
  justify-content: center;
}
// 表格
.el_Commercial_ercial {
  .styled-table {
    width: 100%;
    border-collapse: collapse;
  }
  .tabBox {
    width: 24%;
    margin-right: 20px;
  }
  .styled-table thead tr {
    text-align: left;
    color: #000;
    background-color: #f5f8fa;
  }

  .styled-table th,
  .styled-table td {
    padding: 3px 10px;
    border: 1px solid #ddd;
    font-size: 16px;
    font-weight: 400;
  }

  .styled-table tbody tr {
    border-bottom: 1px solid #dddddd;
  }

  .styled-table tbody tr:nth-of-type(even) {
    background-color: #f3f3f3;
  }

  .styled-table tbody tr:last-of-type {
  }

  .el_btn_a {
    color: #409eff;
  }
  .el_btn_b {
    color: #ff0000;
  }
}
.el_translation{
  display: flex;
    width: 100%;
    .el_Storage{
      width: 24%;
      display: flex;
    flex-direction: column;
    margin-right: 24px;
    .el-radio-group {
      width: 100%
    }
    }
}
</style>
