<template>
  <div v-loading="details.loadingObj.pageLoading">
    <el-form label-width="150px" :model="details.form" ref="formRef">
      <!-- 计价方式 -->
      <el-form-item
        label="计价方式"
        prop="trunklinePricingType"
        :rules="[{ required: true, message: '请选择计价方式', trigger: ['blur', 'change'] }]"
      >
        <el-select
          v-model="details.form.trunklinePricingType"
          clearable
          multiple
          placeholder="请选择计价方式"
          style="width: 20vw"
          @change="handleChangePrcieMethod"
        >
          <el-option
            v-for="item in details.priceMethodType"
            :key="item.dictKey"
            :label="item.dictValue"
            :value="item.dictKey"
          />
        </el-select>
      </el-form-item>

      <!-- 是否统一区域计费 -->
      <el-form-item
        label="是否统一区域计费"
        prop="trunklineIsUnifyAreaBill"
        :rules="[
          { required: true, message: '请选择是否统一区域计费', trigger: ['blur', 'change'] },
        ]"
      >
        <el-radio-group v-model="details.form.trunklineIsUnifyAreaBill" class="ml-4">
          <el-radio
            v-for="item in details.isType"
            :key="item.value"
            :label="item.value"
            size="large"
            >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 是否区分品类 -->
      <el-form-item
        label="是否区分品类"
        prop="trunklineIsByCategory"
        :rules="[{ required: true, message: '请选择是否区分品类', trigger: ['blur', 'change'] }]"
      >
        <el-radio-group v-model="details.form.trunklineIsByCategory" class="ml-4">
          <el-radio
            v-for="item in details.isType"
            :key="item.value"
            :label="item.value"
            size="large"
            >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="details.form.trunklineIsByCategory === '1'">
        <el-divider content-position="left">品类管理</el-divider>

        <template v-for="value in details.form.billTemplateDetail" :key="value.title">
          <!-- 附加费品类 -->
          <el-form-item
            label-width="150px"
            v-if="details.form.trunklinePricingType.includes(value.code)"
            :label="value.title"
          >
            <div
              class="el_Storagecategory"
              v-loading="goriesloading"
              element-loading-text="Loading..."
            >
              <div class="el_table_span">
                <div class="el_table_id">序号</div>
                <div class="el_table_title">产品品类</div>
              </div>

              <!-- 表格循环 -->
              <div class="el_table_td" v-for="(item, index) in value.categories">
                <div class="el_table_idNumber">{{ index + 1 }}</div>
                <el-select
                  :ref="value.title + index"
                  class="el_Cselect"
                  v-model="item.goods"
                  filterable
                  clearable
                  placeholder="请选择品类"
                  style="width: 240px"
                  :loading="item.loading"
                  @change="handleChangeCategory(item)"
                  remote
                  reserve-keyword
                  default-first-option
                  :remote-method="value => debounce(remoteMethod(value, item), 500)"
                >
                  <el-option
                    v-for="val in item.goodsArr"
                    :key="val.goodsId"
                    :label="val.goodsName"
                    :value="val.goodsId"
                    :disabled="goodsIds.includes(val.goodsId)"
                  />
                </el-select>
                <div class="el_table_operation">
                  <!-- 新增 -->
                  <span
                    v-if="item.plus"
                    @click="handlePlus(value, index)"
                    class="el_table_operation_span_b"
                    >+
                  </span>
                  <!-- 删除 -->
                  <span
                    v-if="item.reduce"
                    @click="handleReduce(value, index)"
                    class="el_table_operation_span_a"
                    >-
                  </span>
                </div>
              </div>
            </div>
          </el-form-item>
        </template>
      </template>

      <el-divider content-position="left">特殊计费</el-divider>

      <!-- 是否特殊配置 -->
      <el-form-item
        label-width="150px"
        label="是否特殊配置"
        prop="trunklineIsPeculiarSetup"
        :rules="[{ required: true, message: '请选择是否特殊配置', trigger: ['blur', 'change'] }]"
      >
        <el-radio-group v-model="details.form.trunklineIsPeculiarSetup" class="ml-4">
          <el-radio
            v-for="item in details.isType"
            :key="item.value"
            :label="item.value"
            size="large"
            >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="details.form.trunklineIsPeculiarSetup === '0'">
        <el-divider content-position="left">一般计费</el-divider>

        <!-- 是否最低计费 -->
        <el-form-item
          label-width="150px"
          label="是否最低计费"
          prop="trunklineIsMinCost"
          :rules="[{ required: true, message: '请选择是否最低计费', trigger: ['blur', 'change'] }]"
        >
          <el-radio-group v-model="details.form.trunklineIsMinCost" class="ml-4">
            <el-radio
              v-for="item in details.isType"
              :key="item.value"
              :label="item.value"
              size="large"
              >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 最低计费类型 -->
        <el-form-item
          v-if="details.form.trunklineIsMinCost === '1'"
          label-width="150px"
          label="最低计费类型"
          prop="trunklineMinCostType"
          :rules="[{ required: true, message: '请选择最低计费类型', trigger: ['blur', 'change'] }]"
        >
          <el-radio-group v-model="details.form.trunklineMinCostType" class="ml-4">
            <template v-for="item in details.lowestType" :key="item.value">
              <el-radio
                v-if="
                  !item.MappingOrNot || details.form.trunklinePricingType.includes(item.mapValue)
                "
                :label="item.dictKey"
                size="large"
                >{{ item.dictValue }}
              </el-radio>

              <el-radio v-else :label="item.dictKey" size="large" disabled>{{
                item.dictValue
              }}</el-radio>
            </template>
          </el-radio-group>
        </el-form-item>
      </template>
    </el-form>

    <!-- 操作按钮 -->
    <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 lang="ts">
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  defineEmits,
  defineComponent,
  computed,
} from 'vue';
import { debounce, deepClone, getObjType } from '@/utils/util';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getDictionaryBiz } from '@/api/system/dict';
import { $_priceTemplate, $_putpriceTemplate } from '@/api/financialsector/index'; //价格模板
import { postFindCategoryInfo } from '@/api/distribution/CreateOrder.js';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';
const $useStore = useStore();
const $route = useRoute(); //获取地址栏参数
const emit = defineEmits(['request-data']);
defineComponent({
  emits: ['request-data'],
});
// 接收参数
const props = defineProps({
  templateData: Object,
});
console.log(props, '来自父页面参数');
const instance = getCurrentInstance();

// 表单实例
const formRef = ref();

interface categories {
  /** 品类名称 */
  goodsName: string;
  /** 品类id */
  goodsId: string;
  /** 显示新增 */
  plus: boolean;
  /** 显示删除 */
  reduce: boolean;
  /** 品类名映射 */
  goods: string;
  /** 模糊查询存放品类的数组 */
  goodsArr: {}[];
  /** loading */
  loading: boolean;
}

interface BillTemplateDetail {
  /** 标题 */
  title: string;
  /** 对应的code */
  code: string;
  /** 品类数组 */
  categories: categories[];
}

/** 页面数据 */
const details = reactive({
  /** 计价方式集合 */
  priceMethodType: [
    {
      label: '按件',
      value: '0',
    },
    {
      label: '按整车',
      value: '1',
    },
    {
      label: '按方',
      value: '2',
    },
    {
      label: '按重量',
      value: '3',
    },
  ],
  isType: [
    {
      label: '是',
      value: '1',
    },
    {
      label: '否',
      value: '0',
    },
  ],
  /** 最低计费类型集合
   * mapValue 用于映射最低计费类型 当选择的计价方式内与该项中mapValue相同时, 显示其选项
   * 当 MappingOrNot 为false时, 不需要检测, 直接显示
   */
  lowestType: [
    {
      label: '价格',
      value: '0',
      MappingOrNot: false,
    },
    {
      label: '件',
      value: '1',
      mapValue: '0',
      MappingOrNot: true,
    },
    {
      label: '方数(m³)',
      value: '2',
      mapValue: '2',
      MappingOrNot: true,
    },
    {
      label: '重量(kg)',
      value: '3',
      mapValue: '3',
      MappingOrNot: true,
    },
  ],
  /** 表单数据 */
  form: {
    /** 计价方式 */
    trunklinePricingType: [],
    /** 是否统一区域计费 */
    trunklineIsUnifyAreaBill: '0',
    /** 是否区分品类 */
    trunklineIsByCategory: '0',
    /** 是否特殊配置 */
    trunklineIsPeculiarSetup: '0',
    /** 是否最低计费 */
    trunklineIsMinCost: '0',
    /** 最低计费类型 */
    trunklineMinCostType: '1',
    /** 计费模版详情 */
    billTemplateDetail: [] as BillTemplateDetail[],
  },
  /** 初始化form数据 */
  initForm: {},
  /** loading */
  loadingObj: {
    pageLoading: false,
  },
});

/** 被选择的货物 */
const goodsIds = computed(() => {
  const ids = [];

  try {
    if (getObjType(details.form.billTemplateDetail) !== 'array') return;

    for (let i = 0; i < details.form.billTemplateDetail.length; i++) {
      const value = details.form.billTemplateDetail[i];

      if (getObjType(value.categories) !== 'array') continue;
      for (let j = 0; j < value.categories.length; j++) {
        const element = value.categories[j];

        if (element.goodsId || element.goodsId === 0) ids.push(element.goodsId);
      }
    }
  } catch (error) {
    console.log('error :>> ', error);
  }

  console.log('ids :>> ', ids);

  return ids;
});

const goriesloading = ref(false);

/** 计价方式改变时 */
const handleChangePrcieMethod = value => {
  console.log('value :>> ', value);

  let activeItem: any = {};
  for (let i = 0; i < details.lowestType.length; i++) {
    const item = details.lowestType[i];
    if (item.value !== details.form.trunklineMinCostType) continue;
    activeItem = item;
    break;
  }

  if (!activeItem.MappingOrNot) return;
  if (!details.form.trunklinePricingType.includes(activeItem.mapValue))
    details.form.trunklineMinCostType = '0';
};

/** 处理干线计费模式 */
const handleTrunkLinePricingType = response => {
  const { code, data } = response.data;

  if (code !== 200) return;

  details.priceMethodType = data || [];

  const _billTemplateDetailArr = [];
  for (let i = 0; i < details.priceMethodType.length; i++) {
    const value = details.priceMethodType[i];
    if (value.dictKey != '2') {
      const _itemObj = {
        title: value.dictValue + '计费品类',
        code: value.dictKey,
        categories: [
          {
            reduce: false,
            plus: true,
            goodsName: '',
            goodsId: '',
            goods: '',
            goodsArr: [],
            loading: false,
          },
        ],
      };

      if (!props.templateData.request) {
        console.log('123123 :>> ', 123123);
        _billTemplateDetailArr.push(_itemObj);
        continue;
      }

      console.log('222 :>> ', 222);
      const _arr = [];

      // 按件
      if (value.dictKey === '1') {
        const { trunklinePieceCategorys } = props.templateData.request;

        if (trunklinePieceCategorys && trunklinePieceCategorys.length !== 0) {
          for (let i = 0; i < trunklinePieceCategorys.length; i++) {
            const item = trunklinePieceCategorys[i];

            _arr.push({
              reduce: i === 0 ? false : true,
              plus: true,
              goodsName: item.name,
              goodsId: item.id,
              goods: item.name,
              goodsArr: [],
              loading: false,
            });
          }

          _itemObj.categories = _arr;
        }
      }
      // 按重量
      if (value.dictKey === '4') {
        const { trunklineWeightCategorys } = props.templateData.request;

        if (trunklineWeightCategorys && trunklineWeightCategorys.length !== 0) {
          for (let i = 0; i < trunklineWeightCategorys.length; i++) {
            const item = trunklineWeightCategorys[i];

            _arr.push({
              reduce: i === 0 ? false : true,
              plus: true,
              goodsName: item.name,
              goodsId: item.id,
              goods: item.name,
              goodsArr: [],
              loading: false,
            });
          }

          _itemObj.categories = _arr;
        }
      }

      // 按方
      if (value.dictKey === '3') {
        const { trunklineCubeCategorys } = props.templateData.request;

        if (trunklineCubeCategorys && trunklineCubeCategorys.length !== 0) {
          for (let i = 0; i < trunklineCubeCategorys.length; i++) {
            const item = trunklineCubeCategorys[i];

            _arr.push({
              reduce: i === 0 ? false : true,
              plus: true,
              goodsName: item.name,
              goodsId: item.id,
              goods: item.name,
              goodsArr: [],
              loading: false,
            });
          }

          _itemObj.categories = _arr;
        }
      }

      _billTemplateDetailArr.push(_itemObj);
    }
  }

  console.log('_billTemplateDetailArr :>> ', _billTemplateDetailArr);
  details.form.billTemplateDetail = _billTemplateDetailArr;
};

/** 处理最低计费价格 */
const handleLowestPrice = response => {
  console.log('response :>> ', response);
  const { code, data } = response.data;

  if (code !== 200) return;

  const _dataArr = [];

  if (!data) {
  }

  details.lowestType = data || [];
};

/** 复制form初始数据 */
const initFormData = () => {
  details.initForm = deepClone(details.form);
};

/** 获取业务字典 */
const initDictionaryBiz = async () => {
  try {
    // 干线计费方式
    const trunkLinePromise = getDictionaryBiz('trunk_line_pricing_type');
    // 最低计费价格
    const minCostPromise = getDictionaryBiz('min_cost_type');

    const [trunkLineResult, minCostResult] = await Promise.all([trunkLinePromise, minCostPromise]);

    await nextTick();
    console.log('props.templateData.request :>> ', props.templateData.request);

    if (Object.keys(props.templateData).length !== 0) {
      details.form = deepClone(props.templateData.request);

      details.form.trunklinePricingType = details.form.trunklinePricingType
        ? details.form.trunklinePricingType.split(',')
        : [];
      details.form.trunklineIsUnifyAreaBill += '';
      details.form.trunklineIsByCategory += '';
      details.form.trunklineIsPeculiarSetup += '';
      details.form.trunklineIsMinCost += '';
      details.form.trunklineMinCostType += '';
    }

    console.log('details.form :>> ', details.form);

    // 处理干线
    handleTrunkLinePricingType(trunkLineResult);
    handleLowestPrice(minCostResult);

    initFormData();
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
  }
};

initDictionaryBiz();

/** 新增品类 */
const handlePlus = async (value: any, index: number) => {
  value.categories.splice(index + 1, 0, {
    reduce: true,
    plus: true,
    goodsName: '',
    goodsId: '',
    goods: '',
    goodsArr: [],
    loading: false,
  });

  await nextTick();

  instance.ctx.$refs[value.title + (index + 1)][0].focus();
  console.log('instance :>> ', instance.ctx);
};

/** 删除品类 */
const handleReduce = (value: any, index: number) => {
  if (index === 0) return;
  value.categories.splice(index, 1);
};

/** 货物变化时 */
const handleChangeCategory = item => {
  if (!item.goods) {
    item.goodsId = '';
    item.goodsName = '';
    return;
  }

  for (let i = 0; i < item.goodsArr.length; i++) {
    const value = item.goodsArr[i];

    if (item.goods !== value.goodsId) continue;
    item.goodsId = value.goodsId;
    item.goodsName = value.goodsName;
    break;
  }
};

/** 插混品类 */
const remoteMethod = async (value, item) => {
  try {
    if (!value) return;
    item.loading = true;

    const response = await postFindCategoryInfo({ goodsName: value });

    const { code, data } = response.data;

    if (code !== 200) return;

    item.goodsArr = data || [];
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    item.loading = false;
  }
};

/** 重置数据 */
const resetFormData = () => {
  ElMessageBox.confirm('是否重置数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    formRef.value.resetFields();

    details.loadingObj.pageLoading = true;
    details.form = deepClone(details.initForm);
    setTimeout(() => {
      details.loadingObj.pageLoading = false;
    }, 300);
  });
};

/** 提交 */
const handleSubmit = async () => {
  if (details.form.trunklinePricingType.length === 0) ElMessage.error('请选择计价方式');

  formRef.value.validate(async valid => {
    await emit('request-data'); //通知父页面传递数据
    if (!valid) return;
    console.log(props, 'props');
    if (!props.templateData.TemplateName) {
      ElMessage({
        message: '请输入模板名称',
        type: 'warning',
      });
      return;
    } else {
      details.form.name = props.templateData.TemplateName; //模板名称
    }

    if (!props.templateData.brand) {
      ElMessage({
        message: '请选择品牌',
        type: 'warning',
      });
      return;
    } else {
      details.form.brandId = props.templateData.brand; //品牌ID
    }

    details.form.serviceType = props.templateData.ServiceType.join(','); //顶部选择的服务类型
    console.log(details.form, '初始表单');
    const submitData = deepClone(details.form); //深拷贝
    //  计价方式
    submitData.trunklinePricingType = submitData.trunklinePricingType.join(',');
    //品类管理
    // 是否区分品类，选择是才进行处理
    if (details.form.trunklineIsByCategory === '1') {
      submitData.billTemplateDetail.forEach(item => {
        switch (item.code) {
          case '1':
            submitData.trunklinePieceCategory = item.categories
              .filter(res => res.goodsId)
              .map(res => res.goodsId)
              .join(',');
            break;
          case '3':
            submitData.trunklineCubeCategory = item.categories
              .filter(res => res.goodsId)
              .map(res => res.goodsId)
              .join(',');
            break;
          case '4':
            submitData.trunklineWeightCategory = item.categories
              .filter(res => res.goodsId)
              .map(res => res.goodsId)
              .join(',');
            break;
          default:
            break;
        }
      });
    }
    delete submitData.billTemplateDetail; //删除是否区分品类多余参数
    console.log(submitData, '处理好的参数');

    if (props.templateData.code || $route.query.id) {
      let data = {
        id: props.templateData.code, //编辑参数
        ...submitData, //提交的参数
        checkType: '2',
      };
      // 走编辑
      $_putpriceTemplate(data).then(res => {
        console.log(res, '编辑成功之后返回值');
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success',
          });
          $useStore.commit('EDIT_REFRESHITEM', { title: 'CustomerBaseprice', status: true });
        }
      });
    } else {
      // 走新增
      let data = {
        ...submitData, //提交的参数
      };
      $_priceTemplate(data).then(res => {
        console.log(res, '提交成功返回值');
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success',
          });
          $useStore.commit('EDIT_REFRESHITEM', { title: 'CustomerBaseprice', status: true });
          emit('request-data', res.data.data); //把获取到的数据传递给父页面
        }
      });
    }
  });
};
</script>

<style lang="scss" scoped>
// 标题
:deep(.el-divider__text.is-left) {
  font-size: 20px;
  font-weight: bold;
  color: var(--el-color-primary);
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

.el_Cselect {
  margin-left: 10px;
}
.el_table_span {
  font-size: 16px;
  font-weight: 500;
  display: inline-block;
  width: 160px;
}

.el_Storagecategory {
  border: 1px solid #ccc;
  .el_table_span {
    display: flex;
    width: 100%;
    background-color: #ebeef5;
    padding: 4px;
    box-sizing: border-box;
  }
  .el_table_id {
    width: 62px;
    font-weight: 600;
    color: #606266;
  }
  .el_table_title {
    font-weight: 600;
    color: #606266;
  }
  .el_table_td {
    display: flex;
    height: 40px;
    align-items: center;
    border-bottom: 1px solid #ccc;
    position: relative;
    .el_table_operation {
      width: 70px;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: absolute;
      right: -80px;
      .el_table_operation_span_a,
      .el_table_operation_span_b {
        font-size: 20px;
        font-weight: bold;
        width: 40%;
        border: 2px solid #f00;
        color: #f00;
        height: 70%;
        border-radius: 6px;
        display: block;
        line-height: 23px;
        text-align: center;
        cursor: pointer;
      }
      .el_table_operation_span_b {
        border: 2px solid #0d83b7;
        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: 50px;
    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;
  }
}
</style>
