<template>
  <div class="content_max" v-loading="pageLoading">
    <el-form>
      <!-- 配送服务类型 -->
      <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
              style="padding: 0"
              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">
              <!-- 按件  -->
              <el-form-item label="按件计费" v-if="form.dispatchPieceCategoryState">
                <SurchargeTable
                  :SurchargeData="form.dispatchPieceCategoryData"
                  :Surcharge="dispatchPieceCategory"
                  @focus="handleRowFocus"
                  @search="search"
                  @change="selectChange"
                >
                  <template #default="slotProps">
                    <template v-if="slotProps.scope.column.label === '操作'">
                      <div class="eml_btn">
                        <span
                          @click="storageplus"
                          class="el_btn_a"
                          v-if="slotProps.scope.row.index == 1"
                        >
                          <el-icon style="color: #409eff; margin-right: 3px"><CirclePlus /></el-icon
                          >新增
                        </span>
                        <span
                          @click="storagereduce(slotProps.scope.row.index)"
                          class="el_btn_b"
                          v-if="slotProps.scope.row.index != 1"
                        >
                          <el-icon style="color: #f00; margin-right: 3px"><Delete /></el-icon>删除
                        </span>
                      </div>
                    </template>
                  </template>
                </SurchargeTable>
              </el-form-item>

              <el-form-item label="按重量计费" v-if="form.dispatchWeightCategoryState">
                <SurchargeTable
                  :SurchargeData="form.dispatchWeightCategoryData"
                  :Surcharge="dispatchWeightCategory"
                  @focus="handleRowFocus"
                  @search="search"
                  @change="selectChange"
                >
                  <template #default="slotProps">
                    <template v-if="slotProps.scope.column.label === '操作'">
                      <div class="eml_btn">
                        <span
                          @click="categoriesplusweight"
                          class="el_btn_a"
                          v-if="slotProps.scope.row.index == 1"
                        >
                          <el-icon style="color: #409eff; margin-right: 3px"><CirclePlus /></el-icon
                          >新增
                        </span>
                        <span
                          @click="categoriesduceweight(slotProps.scope.row.index)"
                          class="el_btn_b"
                          v-if="slotProps.scope.row.index != 1"
                        >
                          <el-icon style="color: #f00; margin-right: 3px"><Delete /></el-icon>删除
                        </span>
                      </div>
                    </template>
                  </template>
                </SurchargeTable>
              </el-form-item>
              <el-form-item label="按方计费" v-if="form.dispatchCubeCategoryState">
                <SurchargeTable
                  :SurchargeData="form.dispatchCubeCategoryData"
                  :Surcharge="dispatchCubeCategory"
                  @focus="handleRowFocus"
                  @search="search"
                  @change="selectChange"
                >
                  <template #default="slotProps">
                    <template v-if="slotProps.scope.column.label === '操作'">
                      <div class="eml_btn">
                        <span
                          @click="categoriesplussquare"
                          class="el_btn_a"
                          v-if="slotProps.scope.row.index == 1"
                        >
                          <el-icon style="color: #409eff; margin-right: 3px"><CirclePlus /></el-icon
                          >新增
                        </span>
                        <span
                          @click="categoriesducesquare(slotProps.scope.row.index)"
                          class="el_btn_b"
                          v-if="slotProps.scope.row.index != 1"
                        >
                          <el-icon style="color: #f00; margin-right: 3px"><Delete /></el-icon>删除
                        </span>
                      </div>
                    </template>
                  </template>
                </SurchargeTable>
              </el-form-item>
            </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">
            <el-form-item label="附加费品类">
              <SurchargeTable
                :SurchargeData="form.dispatchSubjoinCategoryData"
                :Surcharge="dispatchSubjoinCategory"
                @focus="handleRowFocus"
                @search="search"
              >
                <template #default="slotProps">
                  <template v-if="slotProps.scope.column.label === '操作'">
                    <div class="eml_btn">
                      <span
                        @click="categoriesplusSurcharge"
                        class="el_btn_a"
                        v-if="slotProps.scope.row.index == 1"
                      >
                        <el-icon style="color: #409eff; margin-right: 3px"><CirclePlus /></el-icon
                        >新增
                      </span>
                      <span
                        @click="categoriesduceSurcharge(slotProps.scope.row.index)"
                        class="el_btn_b"
                        v-if="slotProps.scope.row.index != 1"
                      >
                        <el-icon style="color: #f00; margin-right: 3px"><Delete /></el-icon>删除
                      </span>
                    </div>
                  </template>
                </template>
              </SurchargeTable>
            </el-form-item>
          </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>
    </el-form>
  </div>
</template>

<script setup>
import { ref, defineEmits, defineComponent, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getDictionaryBiz } from '@/api/system/dict'; //字典
import { deepClone, fullscreenEnable } from '@/utils/util';
import { postFindCategoryInfo } from '@/api/distribution/CreateOrder.js';
import { $_priceTemplate, $_putpriceTemplate } from '@/api/financialsector/index'; //价格模板
import SurchargeTable from '@/components/pric/tablePric.vue';
import { submit } from '@/api/base/region';
const $route = useRoute(); //获取地址栏参数
const emit = defineEmits(['request-data']);
defineComponent({
  emits: ['request-data'],
});
// 接收参数
const props = defineProps({
  templateData: Object,
});
console.log(props, '来自父页面参数');
const request = ref({}); //接收参数
//表单
const pageLoading = ref(true);
const SelectData = ref({});
const formedit = ref({}); //编辑重置
const formCopy = ref(null); //拷贝的数据
const form = ref({
  dispatchPieceCategoryState: true, //按件是否显示
  dispatchWeightCategoryState: true, //按重量是否显示
  dispatchCubeCategoryState: true, //按方是否显示
  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: '', //标题
  dispatchPieceCategoryData: [], //按件品类
  dispatchWeightCategoryData: [], //按重量
  dispatchCubeCategoryData: [], //按方品类
  dispatchSubjoinCategoryData: [], //附加费品类
});
// 按件品类
const dispatchPieceCategory = ref([
  //按件品类
  { label: '序号', prop: 'index', type: 'string', width: '50', disabled: true },
  {
    label: '产品品类',
    prop: 'Warehousecategory',
    type: 'select',
    width: 'auto',
    disabled: true,
  },
  { label: '操作', prop: '', type: '', width: '80', disabled: true },
]);
// 按重量
const dispatchWeightCategory = ref([
  { label: '序号', prop: 'index', type: 'string', width: '50', disabled: true },
  {
    label: '产品品类',
    prop: 'Warehousecategory',
    type: 'select',
    width: 'auto',
    disabled: true,
  },
  { label: '操作', prop: '', type: '', width: '80', disabled: true },
]);
// 按方品类
const dispatchCubeCategory = ref([
  { label: '序号', prop: 'index', type: 'string', width: '50', disabled: true },
  {
    label: '产品品类',
    prop: 'Warehousecategory',
    type: 'select',
    width: 'auto',
    disabled: true,
  },
  { label: '操作', prop: '', type: '', width: '80', disabled: true },
]);
// 附加费品类
const dispatchSubjoinCategory = ref([
  { label: '序号', prop: 'index', type: 'string', width: '50', disabled: true },
  {
    label: '产品品类',
    prop: 'Warehousecategory',
    type: 'select',
    width: 'auto',
    disabled: true,
  },
  { label: '操作', prop: '', type: '', width: '80', disabled: true },
]);
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: 'Commercialcial', //附加费标识
    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([]);

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

// 是否面配置楼层
const UpstairsChange = val => {
  if (val == 1) {
    form.value.dispatchIsFeeFloor = 0; //初始化参数
  } else {
    form.value.dispatchIsFeeFloor = null; //初始化参数
  }
};
// 是否区分品类
const categoryChange = val => {};
// 是否最低计费展示
const MinimumChange = val => {
  console.log(val);
  if (val) {
    form.value.dispatchMinCostMode = 1;
    form.value.dispatchMinCostType=1
    form.value.dispatchIsUpwardJudgment = 0;
  } else {
    form.value.dispatchMinCostMode = 0;
    form.value.dispatchIsUpwardJudgment = 0; //向上判断
    form.value.dispatchMinCostType=null
  }
};

// 根据当前选择的服务类型来选择是否显示框框

const CommercialcialDisplay = id => {
  let data = ServiceList.value.find(res => res.value == id);
  console.log(ServiceList.value, 'ServiceList.value');
  if (data.value == 1) {
    form.value.dispatchPieceCategoryState = true; //按件是否显示
    form.value.dispatchPieceCategoryData = [
      {
        index: 1,
        Warehousecategory: '',
        options: [],
        plus: true,
        reduce: false,
        StateName: 'storage', //仓储标识
        loading: false,
      },
    ];

    if (data.check) {
      form.value.dispatchPieceCategoryState = true; //按件是否显示
    } else {
      form.value.dispatchPieceCategoryState = false; //按件是否显示
    }
  } else if (data.value == 2) {
    form.value.dispatchWeightCategoryData = [
      {
        index: 1,
        Warehousecategory: '',
        options: [],
        plus: true,
        reduce: false,
        StateName: 'storage', //仓储标识
        loading: false,
      },
    ];
    if (data.check) {
      form.value.dispatchWeightCategoryState = true; //按件是否显示
    } else {
      form.value.dispatchWeightCategoryState = false; //按件是否显示
    }
  } else if (data.value == 3) {
    form.value.dispatchCubeCategoryData = [
      {
        index: 1,
        Warehousecategory: '',
        options: [],
        plus: true,
        reduce: false,
        StateName: 'storage', //仓储标识
        loading: false,
      },
    ];

    if (data.check) {
      form.value.dispatchCubeCategoryState = true; //按件是否显示
    } else {
      form.value.dispatchCubeCategoryState = false; //按件是否显示
    }
  }
};

// 点击菜单
const isChecked = item => {
  console.log(item.value, '点击菜单value');
  if (!form.value.WarehousebillingmodeTitle) {
    ElMessage({
      message: '请先选择仓储计费类型',
      type: 'warning',
    });
    form.value.dispatchPricingType = []; //清空选择

    item.check = false; //取消当前勾选
    return;
  }
  CommercialcialDisplay(item.value); // 根据当前选择的服务类型来选择是否显示框框
  Timedelive(); //加载效果
};
// 点击移除
const removeTag = value => {
  console.log(value, '点击移除value');
  Deliveryloading.value = true;
  // 根据当前选择的服务类型来选择是否显示框框

  let data = ServiceList.value.find(res => res.value == value);
  data.check = false;
  data.state = false;
  CommercialcialDisplay(value); // 根据当前选择的服务类型来选择是否显示框框
  Timedelive(); //加载效果
};

// 移除对象
function removeItemById(array, id) {
  const index = array.findIndex(item => item.index === id);
  if (index !== -1) {
    array.splice(index, 1);
    if(array.length){
      array.forEach((item, index) => {
      item.index = index + 1;
    });
    }

  }
}
// 添加对象
function addItemAfterId(array, StateName) {
  console.log(array);
  const newItem = {
    index: array.length + 1, // 新对象的 ID 为当前数组长度加 1
    plus: false, // 是否显示加号
    reduce: true, // 是否显示减号
    StateName, // 标识
    Warehousecategory: '', // 选择框值
    options: [], // 选择框列表，防止后期需要改动列表值
    loading: false,
  };
  array.push(newItem);
}
// 仓储减
const storagereduce = id => {
  removeItemById(form.value.dispatchPieceCategoryData, id);
};
// 仓储加
const storageplus = () => {
  addItemAfterId(form.value.dispatchPieceCategoryData, 'storage');
};

// 按重量减
const categoriesduceweight = id => {
  removeItemById(form.value.dispatchWeightCategoryData, id);
};
// 按重量加
const categoriesplusweight = () => {
  addItemAfterId(form.value.dispatchWeightCategoryData, 'storage');
};

// 按方计费减
const categoriesducesquare = id => {
  removeItemById(form.value.dispatchCubeCategoryData, id);
};
// 按方计费加
const categoriesplussquare = () => {
  addItemAfterId(form.value.dispatchCubeCategoryData, 'storage');
};
// 附加费减
const categoriesduceSurcharge = id => {
  removeItemById(form.value.dispatchSubjoinCategoryData, id);
};
// 附加费加

const categoriesplusSurcharge = () => {
  addItemAfterId(form.value.dispatchSubjoinCategoryData, 'Commercialcial');
};
// 附加品类加移除对象
function FmremoveItemById(array, id) {
  const index = array.findIndex(item => item.id === id);
  if (index !== -1) {
    array.splice(index, 1);
    if(array.length){
      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);
};

async function updateDictionary(targetArray, dictionaryType) {
  await 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 = []; //清空服务类型
        if(res.data.data && res.data.data.length){
          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.dispatchServiceType,'服务类型aa');


  
      }
  
      // 是否类型
      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 }; //是否向上判断
      }
    })
    .catch(() => {})
    .finally(() => {});
}

const handleRowFocus = data => {
  SelectData.value = data.row;
  console.log(SelectData.value, '  SelectData.value');
  console.log('row:', data.row);
  console.log('column:', data.column);
};
// 品类搜索
const search = val => {
  if (val) {
    let data = {
      goodsName: val,
    };
    SelectData.value.loading = true;
    postFindCategoryInfo(data)
      .then(res => {
        console.log(res, '附加费品类计费');
        if (res.data.code == 200) {
          if (res.data.data.length) {
            let concatdata = null;
            let data = null;
            SelectData.value.options = []; //如果有新的参数就清空之前的
            console.log(SelectData.value.StateName, 'SelectData.value.StateName');
            if(res.data.data && res.data.data.length){
              res.data.data.forEach(item => {
              if (SelectData.value.StateName == 'storage') {
                //仓储
                concatdata = form.value.dispatchCubeCategoryData.concat(
                  form.value.dispatchWeightCategoryData,
                  form.value.dispatchPieceCategoryData
                );
                data = concatdata.find(res => res.Warehousecategory == item.goodsId);
              } else if (SelectData.value.StateName == 'Commercialcial') {
                //附加费
                data = form.value.dispatchSubjoinCategoryData.find(
                  res => res.Warehousecategory == item.goodsId
                );
              }
              SelectData.value.options.push({
                label: item.goodsName,
                value: item.goodsId,
                disabled: data ? true : false,
              });
            });
            }

          }
        }
      })
      .catch(res => {})
      .finally(() => {
        SelectData.value.loading = false;
      });
  }
};

function updateOptions(allDropdowns) {
    // 拉平所有的下拉框组到一个单一数组中
    let dropdowns = [].concat(...allDropdowns);

    // 遍历每个下拉框
    dropdowns.forEach((dropdown, index, self) => {
        // 取出当前下拉框选中的值
        let selectedValue = dropdown.Warehousecategory;

        // 更新其他下拉框的options状态
        self.forEach(otherDropdown => {
            if (dropdown !== otherDropdown) {  // 确保不是自身
                otherDropdown.options.forEach(option => {
                    // 如果选项值和当前下拉框选中值相同，则禁用该选项
                    if (option.value === selectedValue) {
                        option.disabled = true;
                    } else {
                        // 如果其他逻辑导致应保持禁用，可以在这里加上，下面的语句是检查是否已在别处被选中
                        let isSelectedSomewhereElse = self.some(d => d !== otherDropdown && d.Warehousecategory === option.value);
                        option.disabled = isSelectedSomewhereElse;
                    }
                });
            }
        });
    });
}



// 构造一个包括所有下拉列表的数组

// 选择框值发生改变
const selectChange = data => {
// console.log(data, 'data');
// console.log(form.value.dispatchCubeCategoryData,'dispatchCubeCategoryData111');
// console.log(form.value.dispatchWeightCategoryData,'dispatchWeightCategoryData222');
// console.log(form.value.dispatchPieceCategoryData,'dispatchPieceCategoryData333');

let allDropdowns = [form.value.dispatchCubeCategoryData, form.value.dispatchWeightCategoryData, form.value.dispatchPieceCategoryData];
// 更新选项
updateOptions(allDropdowns);

};
const categoriesSearchfocus = item => {
  console.log(item, 'item');
  SelectOpin.value = item; //获取当前点击的是那个品类输入框
};
// 附加费是否按品类计费
const SurchargeChange = val => {
  if (val) {
    form.value.dispatchSubjoinCategoryData = [
          {
            index: 1,
            Warehousecategory: '',
            options: [],
            plus: true,
            reduce: false,
            StateName: 'Commercialcial',
            loading: false,
          },
        ];
  }
};

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(async () => {
    pageLoading.value = true;
    if ($route.query.id) {
      console.log(form.value.dispatchPricingType, 'form.value.dispatchPricingType');
      form.value = await deepClone(formedit.value);
      if(ServiceList.value.length){
        ServiceList.value.forEach((res, index) => {
        console.log(res);

        if (form.value.dispatchPricingType.includes(res.value)) {
          console.log(res, '选中的');
          res.check = true;
        } else {
          console.log(res, '未选中的');
          res.check = false;
        }
      });
      }

    } else {
      clink();
      Commercialcial.value = deepClone(CommercialcialCopy.value);
      form.value = deepClone(formCopy.value);
    }

    setTimeout(() => {
      pageLoading.value = false;
      ElMessage({
        message: '重置成功',
        type: 'success',
      });
    }, 300);
  });
};

// 页面初始化必要请求
const onLoad = async () => {
  await updateDictionary(ServiceList.value, 'dispatch_pricing_type'); //仓储计费类型
  await updateDictionary(Warehousebillingmode.value, 'dispatch_type'); //仓储计费类型
  await updateDictionary(Distinguishcategories.value, 'price_yes_no'); //是否区分品类
  await updateDictionary(Billingmethod.value, 'min_cost_way'); //是否区分品类
  await updateDictionary(chargetypeSelect.value, 'min_cost_type'); //最低计费类型
  formCopy.value = await deepClone(form.value);
  // 编辑回显
  if (props.templateData.request) {
    console.log('执行回显');
    request.value = await deepClone(props.templateData.request);
    form.value = await deepClone(request.value);

    form.value.dispatchPricingType = request.value.dispatchPricingType
      ? request.value.dispatchPricingType.split(',').map(Number)
      : []; //服务类型
    if(ServiceList.value.length){
      ServiceList.value.forEach(dataItem => {
      if (form.value.dispatchPricingType.includes(dataItem.value)) {
        dataItem.check = true;
        if (dataItem.value == 1) {
          form.value.dispatchPieceCategoryState = true; //按件是否显示
        } else if (dataItem.value == 2) {
          form.value.dispatchWeightCategoryState = true; //按重量是否显示
        } else if (dataItem.value == 3) {
          form.value.dispatchCubeCategoryState = true; //按方是否显示
        }
      }
    });
    }


    StateDelivery.value = true; //显示表格
    form.value.dispatchPieceCategoryData = [];
    if (request.value.dispatchPieceCategory) {
      if (request.value.dispatchPieceCategorys.length) {
        request.value.dispatchPieceCategorys.forEach((res, index) => {
          form.value.dispatchPieceCategoryData.push({
            index: index + 1,
            Warehousecategory: res.id,
            options: [
              {
                label: res.name,
                value: res.id,
              },
            ],
            plus: true,
            reduce: false,
            StateName: 'storage', //仓储标识
            loading: false,
          });
        });
      }
    } else {
      form.value.dispatchPieceCategoryData.push({
        index: 1,
        Warehousecategory: '',
        options: [],
        plus: true,
        reduce: false,
        StateName: 'storage', //仓储标识
        loading: false,
      });
    }
    // 按重量
    form.value.dispatchWeightCategoryData = [];
    if (request.value.dispatchWeightCategory) {
      if (request.value.dispatchWeightCategorys.length) {
        request.value.dispatchWeightCategorys.forEach((res, index) => {
          form.value.dispatchWeightCategoryData.push({
            index: index + 1,
            Warehousecategory: res.id,
            options: [
              {
                label: res.name,
                value: res.id,
              },
            ],
            plus: true,
            reduce: false,
            StateName: 'storage', //仓储标识
            loading: false,
          });
        });
      }
    } else {
      form.value.dispatchWeightCategoryData.push({
        index: 1,
        Warehousecategory: '',
        options: [],
        plus: true,
        reduce: false,
        StateName: 'storage', //仓储标识
        loading: false,
      });
    }
    // 按方
    form.value.dispatchCubeCategoryData = [];
    if (request.value.dispatchCubeCategory) {
      if (request.value.dispatchCubeCategorys.length) {
        request.value.dispatchCubeCategorys.forEach((res, index) => {
          form.value.dispatchCubeCategoryData.push({
            index: index + 1,
            Warehousecategory: res.id,
            options: [
              {
                label: res.name,
                value: res.id,
              },
            ],
            plus: true,
            reduce: false,
            StateName: 'storage', //仓储标识
            loading: false,
          });
        });
      }
    } else {
      form.value.dispatchCubeCategoryData.push({
        index: 1,
        Warehousecategory: '',
        options: [],
        plus: true,
        reduce: false,
        StateName: 'storage', //仓储标识
        loading: false,
      });
    }

    // 附加品类回显
    form.value.dispatchSubjoinCategoryData = [];
    if (request.value.dispatchSubjoinCategory) {
      if (request.value.dispatchSubjoinCategorys.length) {
        request.value.dispatchSubjoinCategorys.forEach((res, index) => {
          form.value.dispatchSubjoinCategoryData.push({
            index: index + 1,
            Warehousecategory: res.id,
            options: [
              {
                label: res.name,
                value: res.id,
              },
            ],
            plus: true,
            reduce: false,
            StateName: 'Commercialcial',
            loading: false,
          });
        });
      } else {
        form.value.dispatchSubjoinCategoryData = [
          {
            index: 1,
            Warehousecategory: '',
            options: [],
            plus: true,
            reduce: false,
            StateName: 'Commercialcial',
            loading: false,
          },
        ];
    
      }
    }
    if (form.value.dispatchServiceType) {
          form.value.WarehousebillingmodeTitle = Warehousebillingmode.value.find(
            res => res.value == form.value.dispatchServiceType
          ).label;
        }
  }
  formedit.value = await deepClone(form.value);
  pageLoading.value = false;
};
onLoad();
// 保存事件
const handleSubmit = async () => {
  console.log(form.value.dispatchPieceCategoryData, 'form.value.dispatchPieceCategoryData');

  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(','); //顶部选择的服务类型
    // 初始化数据
    const Submit = deepClone(form.value); //拷贝一份要提交的数据

    Submit.dispatchPricingType = Submit.dispatchPricingType.join(','); //服务类型处理

    // 选择了是否区分品类才进行处理数据
    if (form.value.dispatchIsByCategory) {
      console.log('区分品类了');
      if (!form.value.dispatchPricingType.includes(1)) {
        Submit.dispatchPieceCategory = '';
      } else {
        if (form.value.dispatchPieceCategoryData.find(res => !res.Warehousecategory)) {
          ElMessage({
            message: '请填写完整按件计费品类',
            type: 'warning',
          });
          return;
        }
        Submit.dispatchPieceCategory = form.value.dispatchPieceCategoryData
          .map(res => res.Warehousecategory)
          .join(',');
        // dispatchPieceCategoryData 件
        // dispatchWeightCategoryData  重量
        // dispatchCubeCategoryData 方
      }
      if (!form.value.dispatchPricingType.includes(2)) {
        Submit.dispatchWeightCategory = '';
      } else {
        if (form.value.dispatchWeightCategoryData.find(res => !res.Warehousecategory)) {
          ElMessage({
            message: '请填写完整按重量计费品类',
            type: 'warning',
          });
          console.log(form.value.dispatchWeightCategoryData, 'cascasdasd=>>');
          return;
        }
        Submit.dispatchWeightCategory = form.value.dispatchWeightCategoryData
          .map(res => res.Warehousecategory)
          .join(',');
      }
      if (!form.value.dispatchPricingType.includes(3)) {
        Submit.dispatchCubeCategory = '';
      } else {
        if (form.value.dispatchCubeCategoryData.find(res => !res.Warehousecategory)) {
          ElMessage({
            message: '请填写完整按方计费品类',
            type: 'warning',
          });
          return;
        }

        Submit.dispatchCubeCategory = form.value.dispatchCubeCategoryData
          .map(res => res.Warehousecategory)
          .join(',');
      }
    } else {
      Submit.dispatchPieceCategory = '';
      Submit.dispatchWeightCategory = '';
      Submit.dispatchCubeCategory = '';
    }

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

    console.log(Submit, '要提交的数据');
    ElMessageBox.confirm('是否保存?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    pageLoading.value=true
    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',
          });
        }
      }).catch(res=>{
        console.log(res,'错误信息');
      }).finally(()=>{
        pageLoading.value=false
      });
    } 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); //把获取到的数据传递给父页面
        }
      }).catch(res=>{
        console.log(res,'错误信息');
      }).finally(()=>{
        pageLoading.value=false
      });;
    }
  });
};
</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::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: 24%;
    .el-form-item {
      flex-direction: column;
      width: 100%;
      margin-right: 0;
      .el-form-item__content {
        align-items: flex-start !important;
      }
    }
  }
}

: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-form-item {
      width: 24%;
      flex-direction: column;
      .el-form-item__content {
        align-items: flex-start !important;
      }
    }
  }
}
.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%;
    }
  }
}
:deep(.el_row_table) {
  thead {
    th {
      background-color: #f5f8fa;
      color: #172e60;
    }
    .cell {
      padding: 0 10px;
    }
  }
  tbody {
    .el-table tr:hover {
      background-color: transparent;
    }

    .cell {
      text-align: center;
      padding: 0 10px;
      .el-input-number {
        width: 100%;
        .el-input__wrapper {
          box-shadow: none;
        }

        .el-input__inner:hover {
          box-shadow: 0px 1px 0vw 0px #172e60;
        }
      }
    }
  }
}
.eml_btn {
  .el_btn_a,
  .el_btn_b {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
}
</style>
