<template>
  <div class="content_box" v-loading="pageLoading" element-loading-text="页面正在加载中...">
    <div class="header">
      <!-- 模板名称 -->
      <div class="el_Template">
        <span class="name">模板名称</span>
        <el-input v-model="form.TemplateName" style="width: 240px" placeholder="请输入模板名称" />
      </div>

      <!-- 品牌  -->
      <div class="el_Service">
        <span class="name">品牌</span>
        <el-select
          v-model="form.brand"
          filterable
          placeholder="请选择品牌"
          :popper-append-to-body="false"
          style="width: 340px"
        >
          <el-option
            v-for="item in brand"
            :key="item.value"
            :label="item.brandName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>

      <!-- 服务类型  -->
      <div class="el_Service">
        <span class="name">服务类型</span>
        <el-select
          v-model="form.ServiceType"
          filterable
          placeholder="请选择服务类型"
          :popper-append-to-body="false"
          style="width: 340px"
          multiple
          @change="handleChange"
          @remove-tag="removeTag"
          :loading="ServiceTypeLoading"
        >
          <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, true, true)">
              {{ item.label }}
            </el-checkbox>
          </el-option>
        </el-select>
      </div>
    </div>

    <!-- 模板内容 -->
    <div class="content">
      <el-tabs type="border-card" 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" :templateData="templateInfo"
            /></span>
            <span v-if="item.label == '干线'"
              ><FinancialTrunkLine @request-data="provideData" :templateData="templateInfo"
            /></span>
            <span v-if="item.label == '仓储'"
              ><FinancialWarehousing @request-data="provideData" :templateData="templateInfo"
            /></span>
            <span v-if="item.label == '配送'"
              ><FinancialDelivery @request-data="provideData" :templateData="templateInfo"
            /></span>
            <span v-if="item.label == '安装'">安装</span>
          </el-tab-pane>
        </template>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, defineAsyncComponent, getCurrentInstance } from 'vue';
import { getDictionaryBiz } from '@/api/system/dict'; //字典
import {
  $_basicdataBrande,
  $_InfopriceTemplate,
  $_tempDelpriceTemplate,
} from '@/api/financialsector/index'; //价格模板
import { ElMessage, ElMessageBox } from 'element-plus';
const $route = useRoute(); //获取地址栏参数
const pageLoading = ref(true); //页面加载效果

// vue实例
const instance = getCurrentInstance();
//仓储模板
const FinancialWarehousing = defineAsyncComponent(() =>
  import('@/views/financialsector/Financialse/FinancialWarehousing.vue')
);
/** 提货模板 */
const FinancialBill = defineAsyncComponent(() =>
  import('@/views/financialsector/Financialse/FinancialBill.vue')
);
/** 干线模板 */
const FinancialTrunkLine = defineAsyncComponent(() =>
  import('@/views/financialsector/Financialse/FinancialTrunkLine.vue')
);
// 配送模板
const FinancialDelivery = defineAsyncComponent(() =>
  import('@/views/financialsector/Financialse/FinancialDelivery.vue')
);
const ServiceTypeLoading = ref(true); //菜单加载
const form = ref({});
const brand = ref([]); //品牌
const Tabmenu = ref('仓储');
const request = ref({}); //用于保存会显的值
const templateInfo = ref({});
// 菜单列表
const ServiceList = ref([]);
// 字典公共函数 
async function updateDictionary(targetArray, dictionaryType) { 
await  getDictionaryBiz(dictionaryType)
    .then(res => {
      console.log(res, '字典');
      if (res.data.code == 200) {
        if (res.data.data.length) {
          res.data.data.forEach(item => {
            targetArray.push({
              value: item.dictKey,
              label: item.dictValue,
              id: item.id,
            });
          });
        }
      }
    })
    .catch(() => {})
    .finally(() => {
      ServiceTypeLoading.value = false;
    });
}

// 循环渲染菜单
async function executeCheckedResults(results) {
  for (const res of results) {
    await new Promise(resolve => setTimeout(resolve, 500));
    await isChecked(res, false, false);
    await provideData();
  }
  pageLoading.value = false;
  console.log(results,'results');

}
// 页面初始化必要请求
const onLoad = async () => {
  await updateDictionary(ServiceList.value, 'service_type'); //菜单加载
  if ($route.query.id) {
    let data = {
      id: $route.query.id,
    };
    $_InfopriceTemplate(data).then(async res => {
      console.log(res, '获取详情');
      if (res.data.code == 200) {
        request.value = res.data.data; //发送回显数据
        form.value.brand = res.data.data.brandId || ''; //品牌
        form.value.TemplateName = res.data.data.name || ''; //模板名称
        form.value.ServiceType = res.data.data.serviceType.split(',') || []; //服务类型

        console.log('form.value.ServiceType :>> ', form.value.ServiceType);
        const result = await ServiceList.value.filter(item =>
          form.value.ServiceType.includes(item.value)
        );
        // 激活菜单设置为已经存在的
       await executeCheckedResults(result);
        Tabmenu.value=result[0].label;//设置第一个菜单
      }
    });
  } else {
    pageLoading.value = false;
  }
  let data = {
    current: 1,
    size: 1000,
  };
  $_basicdataBrande(data).then(res => {
    console.log(res, '品牌');
    if (res.data.code == 200) {
      brand.value = res.data.data;
    }
  });
};
onLoad();
// 点击菜单
const isChecked = async (val, isChecked = false, msg = false) => {
  console.log(msg, '当前msg');
  console.log(val, 'val');
   if  (msg) {
    val.state =  !val.state;
    Tabmenu.value = val.label;
    if (!val.check) {
      form.value.ServiceType.push(val.value);
      console.log(form.value.ServiceType, '  form.value.ServiceType');
      val.check = true;
      val.state = true;
      ElMessageBox.confirm('关闭当前模板会重置数据！是否关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then( async () => {
          val.check = false;
          val.state = false;
          let indexToRemove = await form.value.ServiceType.findIndex(item => item == val.value);
          if (indexToRemove !== -1) {
            form.value.ServiceType.splice(indexToRemove, 1);
          }
          if (form.value.ServiceType.length) {
            Tabmenu.value = ServiceList.value.find(res => res.state).label;
          }
          if ($route.query.id || templateInfo.value.code) {
            let data = {
              checkType: val.value,
              templateId: $route.query.id,
            };
            $_tempDelpriceTemplate(data).then(res => {
              console.log(res, '删除成功返回值');
              if (res.data.code == 200) {
                ElMessage({
                  type: 'success',
                  message: res.data.msg,
                });
              }
            });
          } else {
            ElMessage({
              type: 'success',
              message: '操作成功',
            });
          }
        })
        .catch(() => {
          val.state = true;
          val.check = true;
        });
    }
  } else {
    console.log(val, 'val');
    //菜单隐藏/显示
    val.state = !val.state;
    if ($route.query.id && !isChecked) {
      val.check = !val.check;
    }
    // 激活菜单设置为已经存在的
    //设置激活菜单
    Tabmenu.value = val.label;
    // 如果当前菜单被关闭则显示最新菜单
    if (!val.state && form.value.ServiceType.length) {
      Tabmenu.value = ServiceList.value.find(res => res.state).label;
    }
  }
};
// 点击移除
const removeTag = value => {
  form.value.ServiceType.push(value);//先加回去
  console.log(value,'value');
  ElMessageBox.confirm('关闭当前模板会重置数据！是否关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then( async () => {
          let indexToRemove = await form.value.ServiceType.findIndex(item => item == value);
          if (indexToRemove !== -1) {
            form.value.ServiceType.splice(indexToRemove, 1);
          }
          if (form.value.ServiceType.length) {
            Tabmenu.value = ServiceList.value.find(res => res.state).label;
          }
          if ($route.query.id || templateInfo.value.code) {
            let data = {
              checkType:value,
              templateId: $route.query.id,
            };
            $_tempDelpriceTemplate(data).then(res => {
              console.log(res, '删除成功返回值');
              if (res.data.code == 200) {
                ElMessage({
                  type: 'success',
                  message: res.data.msg,
                });
                // 激活菜单设置为已经存在的
              if (form.value.ServiceType.length) {
              Tabmenu.value = ServiceList.value.find(res => res.state).label;
               }
              }
            });
          } else {
      
            ElMessage({
              type: 'success',
              message: '操作成功',
            });
          }
          ServiceList.value.find(res => res.value == value).check = false;
            ServiceList.value.find(res => res.value == value).state = false;
        })







};
//   给子页面传递数据
const provideData = data => {
  console.log(data, '来自子页面的数据');
  console.log(form.value, 'form.value');
  templateInfo.value = form.value;
  if (data) {
    templateInfo.value.code = data; //接收来自子页面第一次保存的返回值
  }
  if ($route.query.id) {
    templateInfo.value.request = request.value; //发送回显数据
  }
};

const handleChange = () => {
  instance.ctx.$forceUpdate();
};
</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 !important;
  }
}

.el-select-dropdown__item::after {
  content: '';
  display: none;
}
.content {
  margin-top: 6px;
  height: 100%;
}
</style>
