<template>
  <basic-container v-loading="pageLoading"    element-loading-text="页面正在拼命加载中...">
    <!-- 模板内容 -->
    <div class="content">
      <el-tabs  type="border-card" @tab-click="handleClick" v-model="Tabmenu">
        <template v-for="item in ServiceList" :key="item.label">
          <el-tab-pane :name="item.label" v-if="item.state" :label="item.label">
            <span v-if="item.label == '提货'"
              ><FinancialBill
                @request-data="provideData"
                ref="financialBill"
                :templateData="templateInfo"
            /></span>
            <span v-if="item.label == '干线'"
              ><FinancialTrunkLine
                ref="financialTrunkLine"
                @request-data="provideData"
                :templateData="templateInfo"
            /></span>
            <span v-if="item.label == '仓储'"
              ><FinancialWarehousing
                ref="financialWarehousing"
                @request-data="provideData"
                :templateData="templateInfo"
            /></span>
            <span v-if="item.label == '配送'"
              ><FinancialDelivery
                ref="financialDelivery"
                @request-data="provideData"
                :templateData="templateInfo"
            /></span>
            <span v-if="item.label == '安装'">安装</span>
          </el-tab-pane>
        </template>
      </el-tabs>
    </div>
  </basic-container>
</template>

<script setup>
import { ref, defineAsyncComponent } from 'vue';
import { getDictionaryBiz } from '@/api/system/dict'; //字典
import { $_basicdataBrande } from '@/api/financialsector/index'; //价格模板
import { $_InfopriceTemplate as getInfo, getBasicdataPrice } from '@/api/Pricesystem/index.js';
import { getLazyTreeAll } from '@/api/base/region';
import { $_InfopriceTemplate } from '@/api/financialsector/index.js';
import { useRoute } from 'vue-router';
import { nextTick } from 'vue';
const $route = useRoute();

//仓储模板
const FinancialWarehousing = defineAsyncComponent(() =>
  import('@/views/Pricesystem/Price/PriceWarehousing.vue')
);
/** 提货模板 */
const FinancialBill = defineAsyncComponent(() => import('@/views/Pricesystem/Price/PriceBill.vue'));
/** 干线模板 */
const FinancialTrunkLine = defineAsyncComponent(() =>
  import('@/views/Pricesystem/Price/PriceTrunkLine.vue')
);
// 配送模板
const FinancialDelivery = defineAsyncComponent(() =>
  import('@/views/Pricesystem/Price/PriceDelivery.vue')
);
/** 页面loading */
const pageLoading = ref(true); //菜单加载
const form = ref({});
const Tabmenu = ref('提货');
const templateInfo = ref({});
// 菜单列表
const ServiceList = ref([]);
/** 车辆类型 */
const VehicleTypeList = ref([]);

const financialBill = ref();
const eltabs=ref()
const financialTrunkLine = ref();

const financialDelivery = ref();

const financialWarehousing = ref();
// 字典公共函数
async function updateDictionary(targetArray, dictionaryType) {
  await getDictionaryBiz(dictionaryType)
    .then(res => {
      const { code, data } = res.data;

      if (code !== 200 || !data) return;

      for (const iterator of data) {
        targetArray.push({
          value: iterator.dictKey,
          label: iterator.dictValue,
          id: iterator.id,
        });
      }
    })
    .catch(() => {});
}

// 循环渲染菜单
async function executeCheckedResults(results) {
  console.log('results :>> ', results);

  await nextTick();
  for (const res of results) {
    await isChecked(res, false);
    await provideData();
  }
  pageLoading.value = false;
  Tabmenu.value=results[0].label;//设置第一个菜单
}

/** 获取回显数据 */
const initData = async () => {
  try {
    const res = await getInfo({ id: $route.query.id });

    const { code, data } = res.data;

    if (code !== 200) return;
    form.value.requestInfo = data; //发送回显数据
    // form.value = data;
  } catch (error) {
    console.log('error :>> ', error);
  }
};

// 页面初始化必要请求
const onLoad = async () => {
  console.log(eltabs.value,'eltabssss');
  try {
    pageLoading.value = true;

    // const PromiseAll = [
    //   /** 车辆类型 */
    //   updateDictionary(VehicleTypeList.value, 'price_vehicle_type'),
    // ];

    // await Promise.all(PromiseAll);

    // 干线计费方式
    const trunkLinePromise = getDictionaryBiz('trunk_line_pricing_type');
    // 车辆类型
    const priceVehiclePromise = getDictionaryBiz('price_vehicle_type');

    const regionOptionePromise = await getLazyTreeAll();

    const [trunkLineResult, priceVehicleResult, regionOptione] = await Promise.all([
      trunkLinePromise,
      priceVehiclePromise,
      regionOptionePromise,
      /** 服务类型 */
      updateDictionary(ServiceList.value, 'service_type'),
    ]);

    form.value.trunkLineResult = trunkLineResult;
    form.value.priceVehicleResult = priceVehicleResult;
    form.value.regionOptione = regionOptione;

    console.log('VehicleTypeList :>> ', VehicleTypeList);
    let data = {
      id: $route.query.templateId,
    };
    $_InfopriceTemplate(data).then(async res => {
      const { code, data } = res.data;

      if (code !== 200 || !data) return;

      console.log(res, '获取详情');
      form.value.TemplateName = data.name || ''; //模板名称
      form.value.ServiceType = data.serviceType.split(',') || []; //服务类型
      form.value.request = data;
      form.value.request = data;
      console.log('form.value.ServiceType :>> ', form.value.ServiceType);
      const result = ServiceList.value.filter(item => form.value.ServiceType.includes(item.value));
      await initData();
      // 激活菜单设置为已经存在的
      executeCheckedResults(result);

      await nextTick();
      setTimeout(() => {
        console.log('financialBill :>> ', financialBill);
        if (financialBill.value && financialBill.value.length) {
          financialBill.value[0].initDictionaryBiz();
        }
        if (financialTrunkLine.value && financialTrunkLine.value.length) {
          financialTrunkLine.value[0].initDictionaryBiz();
        }
      }, 1000);
    });
  } catch (error) {
    console.log('error :>> ', error);
    pageLoading.value = false;
  }
};
onLoad();

// 点击菜单
const isChecked =async (val, isCheck = false) => {
  //菜单隐藏/显示
  val.state = !val.state;
  //设置激活菜单
  if (!isCheck) Tabmenu.value = await val.label;
  // 如果当前菜单被关闭则显示最新菜单
  if (!val.state && form.value.ServiceType.length) {
    Tabmenu.value = ServiceList.value.find(res => res.state).label;
  }
};
// 点击移除
const removeTag = value => {
  ServiceList.value.find(res => res.value == value).check = false;
  ServiceList.value.find(res => res.value == value).state = false;
  // 激活菜单设置为已经存在的
  if (form.value.ServiceType.length) {
    Tabmenu.value = ServiceList.value.find(res => res.state).label;
  }
};

//   给子页面传递数据
 const provideData = async data => {
  console.log(data, '来自子页面的数据');
  console.log(form.value, 'form.value');

  templateInfo.value = form.value;
  if (data) {
    templateInfo.value.code = await data; //接收来自子页面第一次保存的返回值
  }
};

const handleClick = (tab, event) => {
  console.log(tab, event);
};
</script>

<style scoped lang="scss">
.content_box {
  width: 100%;
  height: 100%;
}
.header {
  border-bottom: 1px solid #ccc;
  padding: 10px;
  box-shadow: -1px -1px 3px;
  .el_Template {
    display: flex;
    align-items: center;
    .name {
      font-size: 16px;
      margin-right: 10px;
    }
  }
  display: flex;
  .el_Service {
    margin-left: 30px;
    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;
}
.content {
  margin-top: 6px;
  height: 100%;
}
</style>
