<template>
  <div v-loading="details.loadingObj.pageLoading">
    <!-- 是否按统一区域计费 -->
    <template v-if="details.form.pickupIsUnifyAreaBill === '1'">
      <el-form label-width="130px" :model="details.form" ref="formRef">
        <!-- 计费类型 -->
        <el-form-item
          label="计费类型"
          prop="pickupPricingType"
          :rules="[{ required: true, message: '请选择计价方式', trigger: ['blur', 'change'] }]"
        >
          <el-select
            disabled
            v-model="details.form.pickupPricingType"
            clearable
            multiple
            placeholder="请选择计价方式"
            style="width: 20vw"
          >
            <el-option
              v-for="item in details.priceMethodType"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 整车计费 -->
      <template v-if="details.form.pickupPricingType.includes('2')">
        <el-divider content-position="left">整车计费</el-divider>

        <table class="table" border style="border-collapse: collapse">
          <thead class="header">
            <tr align="center">
              <th class="index">序号</th>
              <th width="200px">车型</th>
              <th width="200px">整车计费 ( 元/车 )</th>
              <th width="100px">操作</th>
            </tr>
          </thead>

          <tbody>
            <tr v-for="(value, index) in details.VehicleBillingDetal" :key="value">
              <td class="index">{{ index + 1 }}</td>
              <td>
                <el-select
                  class="w100"
                  v-model="value.vehicleType"
                  filterable
                  clearable
                  placeholder="请选择车型"
                  @change="handleCheckVehicleType"
                >
                  <el-option
                    v-for="item in details.vehicleTypeArr"
                    :key="item.dictKey"
                    :label="item.dictValue"
                    :value="item.dictKey"
                    :disabled="item.isCheck === true"
                  />
                </el-select>
              </td>
              <td>
                <el-input-number
                  class="w100"
                  v-model="value.price"
                  :controls="false"
                  :precision="2"
                  :value-on-clear="0"
                  :min="0"
                />
              </td>
              <!-- 新增 && 删除 -->
              <td v-if="!$route.query.Viewdetails">
                <el-button
                  v-if="index === 0"
                  @click="() => handlePlusVehicle(index)"
                  class="addButton"
                  icon="CirclePlus"
                  >新 增</el-button
                >
                <el-button
                  v-else
                  @click="() => handleReduceVehicle(index)"
                  class="removeButton"
                  icon="CircleClose"
                  >移 除</el-button
                >
              </td>
            </tr>
          </tbody>
        </table>
      </template>

      <!-- 品类计费 -->
      <template
        v-if="
          details.form.pickupPricingType.includes('1') ||
          details.form.pickupPricingType.includes('3') ||
          details.form.pickupPricingType.includes('4')
        "
      >
        <el-divider content-position="left">品类管理</el-divider>

        <div class="billTemplateDetail_container">
          <template v-for="value in details.form.billTemplateDetail" :key="value.title">
            <!-- 是否勾选该计费类型 -->
            <template v-if="details.form.pickupPricingType.includes(value.code)">
              <!-- 是否区分品类计费 -->
              <template v-if="details.form.pickupIsByCategory === '0'">
                <!-- 附加费品类最低计费 -->
                <div>
                  <div class="title">{{ value.title }}</div>

                  <el-input-number
                    v-model="value.categories[0].price"
                    style="width: 13vw"
                    :controls="false"
                    :precision="2"
                    :value-on-clear="0"
                    :min="0"
                  />
                </div>
              </template>

              <template v-else>
                <!-- 附加费品类 -->
                <div>
                  <div class="title">{{ value.title }}</div>

                  <table class="table" border>
                    <thead class="header">
                      <tr>
                        <th class="index">序号</th>
                        <th width="200px">产品品类</th>
                        <th width="200px">按件计费(元/件)</th>
                      </tr>
                    </thead>

                    <tbody>
                      <tr v-for="(item, index) in value.categories">
                        <td class="index">{{ index }}</td>
                        <!-- 品类名称 -->
                        <td>{{ item.name }}</td>
                        <!-- 费用 -->
                        <td>
                          <el-input-number
                            class="w100"
                            v-model="item.price"
                            style="width: 100%"
                            :controls="false"
                            :precision="2"
                            :value-on-clear="0"
                            :min="0"
                          />
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </template>
            </template>
          </template>
        </div>
      </template>

      <template v-if="details.form.pickupIsMinCost === '1'">
        <!-- 最低计费 -->
        <el-divider content-position="left">最低计费</el-divider>
        <el-form label-width="130px" :model="details.form" inline>
          <el-form-item
            :label="
              details.minCostType.find(val => val.value === Number(details.form.pickupMinCostType))
                .label
            "
            prop="minCost"
          >
            <el-input-number
              v-model="details.form.minCost"
              style="width: 13vw"
              :controls="false"
              :value-on-clear="0"
              :min="0"
            />
          </el-form-item>

          <el-form-item
            label="加算价格"
            prop="additionalCost"
            v-if="Number(details.form.pickupMinCostType) !== 1"
          >
            <el-input-number
              v-model="details.form.additionalCost"
              style="width: 13vw"
              :controls="false"
              :value-on-clear="0"
              :min="0"
            />
          </el-form-item>
        </el-form>
      </template>

      <!-- 操作按钮 -->
      <div class="flex-c-c" v-if="!$route.query.Viewdetails">
        <el-button type="primary" icon="Refresh" @click="resetFormData">重置</el-button>
        <el-button type="primary" icon="Position" @click="handleSubmit">保存</el-button>
      </div>
    </template>

    <!-- 提货路径 -->
    <template v-else>
      <div class="flex-c-sb">
        <el-divider content-position="left">提货路径</el-divider>

        <el-button
          icon="CirclePlus"
          class="ml10"
          type="primary"
          @click="handleAdd"
          v-if="!$route.query.Viewdetails"
        >
          新 增
        </el-button>
      </div>

      <tablecmt
        class="tableNode"
        ref="tableNode"
        :columnList="details.columnList"
        :tableData="details.data"
        :loading="details.loadingObj.list"
      >
        <template #default="slotProps">
          <template v-if="slotProps.scope.column.label === '操作' && !$route.query.Viewdetails">
            <el-text class="button" @click="() => handleEdit(slotProps.scope)"
              ><el-icon>
                <CirclePlus />
              </el-icon>
              编 辑
            </el-text>
            <el-text class="button remove" @click="() => handleRemoveLine(slotProps.scope)">
              <el-icon>
                <Delete />
              </el-icon>
              删 除
            </el-text>
          </template>
        </template>
      </tablecmt>

      <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
        <div></div>
        <el-pagination
          align="right"
          background
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="details.page.current"
          :page-sizes="[30, 50, 80, 120]"
          :page-size="details.page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="details.page.total"
        >
        </el-pagination>
      </div>
    </template>
  </div>

  <el-dialog
    :title="details.lineType === 'add' ? '新增提货路径' : '编辑提货路径'"
    :visible.sync="details.popUpShow.addVsitied"
    width="70%"
    v-model="details.popUpShow.addVsitied"
  >
    <el-form inline :model="details.form" ref="lineFormRef" label-width="130px">
      <el-form-item label="始发地" prop="startCity">
        <el-cascader
          pleceholder="请选择始发地"
          :options="details.regionOptione"
          style="width: 100%"
          v-model="details.form.startCity"
          filterable
          :props="{
            checkStrictly: true,
          }"
          @change="value => handleChangeCity(value, 'start')"
          clearable
        >
          <template #default="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>

      <el-form-item label="目的地" prop="endCity">
        <el-cascader
          pleceholder="请选择目的地"
          :options="details.regionOptione"
          :props="{
            checkStrictly: true,
          }"
          style="width: 100%"
          v-model="details.form.endCity"
          @change="value => handleChangeCity(value, 'end')"
          filterable
          clearable
        >
          <template #default="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>

      <el-form-item
        label="发货单位"
        prop="sendOrg"
        :rules="[{ required: true, message: '请选择发货单位', trigger: ['blur', 'change'] }]"
      >
        <el-select
          v-model="details.form.sendOrg"
          filterable
          clearable
          placeholder="请选择发货单位"
          style="width: 240px"
          :loading="details.loadingObj.loading"
          @change="
            () => {
              details.form.sendOrgId = details.form.sendOrg;
            }
          "
          remote
          reserve-keyword
          default-first-option
          :remote-method="value => debounce(remoteMethod(value), 500)"
        >
          <el-option
            v-for="val in details.sendOrgArr"
            :key="val.id"
            :label="val.clientName"
            :value="val.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 整车计费 -->
    <template v-if="details.form.pickupPricingType.includes('2')">
      <el-divider content-position="left">整车计费</el-divider>

      <table class="table" border style="border-collapse: collapse">
        <thead class="header">
          <tr align="center">
            <th class="index">序号</th>
            <th width="200px">车型</th>
            <th width="200px">整车计费 ( 元/车 )</th>
            <th width="100px">操作</th>
          </tr>
        </thead>

        <tbody>
          <tr v-for="(value, index) in details.VehicleBillingDetal" :key="value">
            <td class="index">{{ index + 1 }}</td>
            <td>
              <el-select
                class="w100"
                v-model="value.vehicleType"
                filterable
                clearable
                placeholder="请选择车型"
                @change="handleCheckVehicleType"
              >
                <el-option
                  v-for="item in details.vehicleTypeArr"
                  :key="item.dictKey"
                  :label="item.dictValue"
                  :value="item.dictKey"
                  :disabled="item.isCheck === true"
                />
              </el-select>
            </td>
            <td>
              <el-input-number
                class="w100"
                v-model="value.price"
                :controls="false"
                :precision="2"
                :value-on-clear="0"
                :min="0"
              />
            </td>
            <td v-if="!$route.query.Viewdetails">
              <el-button
                v-if="index === 0"
                @click="() => handlePlusVehicle(index)"
                class="addButton"
                icon="CirclePlus"
                >新 增</el-button
              >
              <el-button
                v-else
                @click="() => handleReduceVehicle(index)"
                class="removeButton"
                icon="CircleClose"
                >移 除</el-button
              >
            </td>
          </tr>
        </tbody>
      </table>
    </template>

    <!-- 品类计费 -->
    <template
      v-if="
        details.form.pickupPricingType.includes('1') ||
        details.form.pickupPricingType.includes('3') ||
        details.form.pickupPricingType.includes('4')
      "
    >
      <el-divider content-position="left">品类管理</el-divider>

      <div class="billTemplateDetail_container">
        <template v-for="value in details.form.billTemplateDetail" :key="value.title">
          <!-- 是否勾选该计费类型 -->
          <template v-if="details.form.pickupPricingType.includes(value.code)">
            <!-- 是否区分品类计费 -->
            <template v-if="details.form.pickupIsByCategory === '0'">
              <!-- 附加费品类最低计费 -->
              <div>
                <div class="title">{{ value.title }}</div>

                <el-input-number
                  v-model="value.categories[0].price"
                  style="width: 13vw"
                  :controls="false"
                  :precision="2"
                  :value-on-clear="0"
                  :min="0"
                />
              </div>
            </template>

            <template v-else>
              <!-- 附加费品类 -->
              <div>
                <div class="title">{{ value.title }}</div>

                <table class="table" border>
                  <thead class="header">
                    <tr>
                      <th class="index">序号</th>
                      <th width="200px">产品品类</th>
                      <th width="200px">按件计费(元/件)</th>
                    </tr>
                  </thead>

                  <tbody>
                    <tr v-for="(item, index) in value.categories">
                      <td class="index">{{ index }}</td>
                      <!-- 品类名称 -->
                      <td>{{ item.name }}</td>
                      <!-- 费用 -->
                      <td>
                        <el-input-number
                          class="w100"
                          v-model="item.price"
                          style="width: 100%"
                          :controls="false"
                          :precision="2"
                          :value-on-clear="0"
                          :min="0"
                        />
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </template>
          </template>
        </template>
      </div>
    </template>

    <template v-if="details.form.pickupIsMinCost === '1'">
      <!-- 最低计费 -->
      <el-divider content-position="left">最低计费</el-divider>
      <el-form label-width="130px" :model="details.form" inline>
        <el-form-item
          :label="
            details.minCostType.find(val => val.value === Number(details.form.pickupMinCostType))
              .label
          "
          prop="minCost"
        >
          <el-input-number
            v-model="details.form.minCost"
            style="width: 13vw"
            :controls="false"
            :value-on-clear="0"
            :min="0"
          />
        </el-form-item>

        <el-form-item
          label="加算价格"
          prop="additionalCost"
          v-if="Number(details.form.pickupMinCostType) !== 1"
        >
          <el-input-number
            v-model="details.form.additionalCost"
            style="width: 13vw"
            :controls="false"
            :value-on-clear="0"
            :min="0"
          />
        </el-form-item>
      </el-form>
    </template>

    <div slot="footer" class="dialog-footer mt10" v-if="!$route.query.Viewdetails">
      <el-button icon="CircleClose" @click="details.popUpShow.addVsitied = false">关 闭</el-button>
      <el-button type="primary" icon="Position" @click="handleSubmitLine">提 交</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
import { getLazyTreeAll } from '@/api/base/region';
import { debounce, deepClone, setNodeHeight } from '@/utils/util';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getDictionaryBiz } from '@/api/system/dict';
import {
  putBasicdataPrice,
  getPage,
  postSubmit,
  postRemove,
  getDetails,
} from '@/api/Pricesystem/index';
import { useRoute } from 'vue-router';
import { getList } from '@/api/basicdata/basicClient';
const $route = useRoute(); //获取地址栏参数

const instance = getCurrentInstance();

const props = defineProps({
  templateData: Object,
});

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

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

/** 提货路径表单 */
const lineFormRef = ref();

const VehicleBillingFormRef = ref();

// 品类价格
interface categories {
  /** 品类名称 */
  title: string;
  /** 品类id */
  categoryId: string;
  /** 费用 */
  price: number;
}

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

/** 整车计费 */
interface VehicleBilling {
  /** 车型 */
  vehicleType: string;
  /** 车型计费(元/车) */
  price: number;
}

/** 页面数据 */
const details = reactive({
  /** 计价方式集合 */
  priceMethodType: [
    {
      label: '按件',
      value: '0',
    },
    {
      label: '按整车',
      value: '1',
    },
    {
      label: '按方',
      value: '2',
    },
    {
      label: '按重量',
      value: '3',
    },
  ],
  /** 车型类型集合 */
  vehicleTypeArr: [],
  /** 表单数据 */
  form: {
    /** 计价方式 */
    pickupPricingType: [],
    /** 计费模版详情 */
    billTemplateDetail: [] as BillTemplateDetail[],
  },
  /** 整车计费 */
  VehicleBillingDetal: [
    {
      /** 车型 */
      vehicleType: '',
      /** 车型计费(元/车) */
      price: 0,
    },
  ] as VehicleBilling[],
  /** 初始化form数据 */
  initForm: {},
  /** loading */
  loadingObj: {
    pageLoading: false,
    list: false,
    loading: false,
  },
  popUpShow: {
    addVsitied: false,
  },
  /** 提货路线表格表头 */
  columnList: [
    // {
    //   prop: '',
    //   label: '序号',
    //   type: 12,
    //   values: '',
    //   width: 55,
    //   fixed: true,
    // },
    {
      prop: 'startCountyName',
      label: '始发地',
      type: 1,
      values: '',
      width: '150',
      checkarr: [],
      fixed: false,
      // sortable: true,
      head: false,
    },
    {
      prop: 'endCountyName',
      label: '目的地',
      type: 1,
      values: '',
      width: '150',
      checkarr: [],
      fixed: false,
      // sortable: true,
      head: false,
    },
    {
      prop: 'sendOrgName',
      label: '发货单位',
      type: 1,
      values: '',
      width: '150',
      checkarr: [],
      fixed: false,
      // sortable: true,
      head: false,
    },
    {
      prop: '',
      label: '操作',
      type: 6,
      values: '',
      width: '150',
      checkarr: [],
      fixed: false,
      head: false,
    },
  ],
  /** 提货线路数据 */
  data: [],
  /** 提货线路分页参数 */
  page: {
    /** 当前页 */
    current: 1,
    /** 每页页数 */
    size: 30,
    /** 总数 */
    total: 0,
  },
  /** 发货单位数组 */
  sendOrgArr: [],
  /** 省市区 */
  regionOptione: [],
  /** 提货路线type */
  lineType: 'add' as 'add' | 'edit',
  minCostType: [
    { label: '按价格最低计费', value: 1 },
    { label: '按件最低计费', value: 2 },
    { label: '按方数最低计费', value: 3 },
    { label: '按重量最低计费', value: 4 },
  ],
});

const tableNode = ref();

const validatePrice = (rule: any, value: any, callback: any) => {
  const message = '请输入大于0的费用';

  if (!value) {
    callback(new Error(message));
    return false;
  } else if (value <= 0) {
    callback(new Error(message));
    return false;
  } else {
    callback();
  }
};

/** 处理干线计费模式 */
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: [
          {
            title: '',
            categoryId: '',
            goods: '',
            price: 0,
          },
        ],
      };

      if (!props.templateData.request) {
        _billTemplateDetailArr.push(_itemObj);
        continue;
      }

      const _arr = [];

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

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

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

            _arr.push({
              name: item.name,
              categoryId: item.id,
              price: 0,
            });
          }

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

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

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

            _arr.push({
              name: item.name,
              categoryId: item.id,
              price: 0,
            });
          }

          _itemObj.categories = _arr;
        }
      }

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

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

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

            _arr.push({
              name: item.name,
              categoryId: item.id,
              price: 0,
            });
          }

          _itemObj.categories = _arr;
        }
      }

      _billTemplateDetailArr.push(_itemObj);
    }
  }

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

/** 处理车辆类型 */
const handleVehicleTypeArr = response => {
  details.vehicleTypeArr = deepClone(response) || [];
};

/** 获取业务字典 */
const initDictionaryBiz = async () => {
  console.log('123213213 :>> ', 123213213);
  try {
    const { trunkLineResult, priceVehicleResult, regionOptione } = props.templateData;
    // // 干线计费方式
    // const trunkLinePromise = getDictionaryBiz('trunk_line_pricing_type');
    // // 车辆类型
    // const priceVehiclePromise = getDictionaryBiz('price_vehicle_type');

    // const [trunkLineResult, priceVehicleResult] = await Promise.all([
    //   trunkLinePromise,
    //   priceVehiclePromise,
    // ]);

    await nextTick();

    if (Object.keys(props.templateData).length !== 0) {
      console.log('123 :>> ', 123);
      details.form = deepClone(props.templateData.request);

      details.form.pickupPricingType = details.form.pickupPricingType
        ? details.form.pickupPricingType.split(',')
        : [];
      details.form.pickupIsByCategory += '';
      details.form.pickupMinCostType += '';
      details.form.pickupIsUnifyAreaBill += '';
      details.form.pickupIsMinCost += '';
      details.form.minCost = 0;
      details.form.additionalCost = 0;

      // 不按统一区域计费, 初始化获取数据
      if (details.form.pickupIsUnifyAreaBill === '0') {
        console.log('123 :>> ', 123);

        // 获取省市区信息
        if (regionOptione.data.success) {
          details.regionOptione = regionOptione.data.data || [];
        }

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

        initLineData();
      }
    }

    // 处理干线
    handleTrunkLinePricingType(trunkLineResult);
    handleVehicleTypeArr(priceVehicleResult);

    initAssignmentForm(props.templateData.requestInfo.pickup, false);
    // 初始化复制form数据
    initFormData();
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
  }
};

// initDictionaryBiz();

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

/** 新增车辆 */
const handlePlusVehicle = async (index: number) => {
  if (details.VehicleBillingDetal.length === details.vehicleTypeArr.length)
    return ElMessage.warning('已无更多车型, 无法再新增');

  // for (let i = 0; i < details.vehicleTypeArr.length; i++) {
  //   const value = details.vehicleTypeArr[i];
  //   if (value.isCheck) return ElMessage.warning('暂无可选车型');
  // }

  details.VehicleBillingDetal.splice(index + 1, 0, {
    /** 车型 */
    vehicleType: '',
    /** 车型计费(元/车) */
    price: 0,
  });

  // await nextTick();

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

/** 删除车辆 */
const handleReduceVehicle = (index: number) => {
  if (index === 0) return;
  details.VehicleBillingDetal.splice(index, 1);
  handleCheckVehicleType();
};

/** 车型选择 */
const handleCheckVehicleType = () => {
  const codeArr = details.VehicleBillingDetal.map(val => val.vehicleType);

  for (let i = 0; i < details.vehicleTypeArr.length; i++) {
    const value = details.vehicleTypeArr[i];
    value.isCheck = codeArr.includes(value.dictKey) ? true : false;
  }
};

/** 转译始发地和目的地
 * @param {Array} 循环数组
 * @param {String} province 省
 * @param {String} city 市
 * @param {String} region 区
 */
const handleTranslation = (province, city, region) => {
  console.log('province, city, region :>> ', province, city, region);

  let name = '';

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

    if (value.value !== province + '') continue;
    name += value.label;

    if (!value.children || value.children.length === 0) return name;

    for (let index = 0; index < value.children.length; index++) {
      const element = value.children[index];

      if (element.value !== city + '') continue;
      name += '/' + element.label;

      if (!element.children || element.children.length === 0) return name;

      for (let j = 0; j < element.children.length; j++) {
        const item = element.children[j];

        if (item.value === region + '') {
          name += '/' + item.label;
          break;
        }
      }
      break;
    }
    break;
  }

  return name;
};

/** 获取提货路径数据 */
const initLineData = async () => {
  setNodeHeight(tableNode.value.$el, '70vh');

  try {
    details.loadingObj.list = true;

    const res = await getPage({ ...details.page, priceId: $route.query.id, serviceType: '1' });
    const { code, data } = res.data;

    if (code !== 200) return;

    details.data = data.records;

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

      value.startCountyName = handleTranslation(
        value.startProvinceId,
        value.startCityId,
        value.startCountyId
      );
      value.endCountyName = handleTranslation(
        value.endProvinceId,
        value.endCityId,
        value.endCountyId
      );
    }

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

    details.page.total = data.total;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.list = false;
  }
};

/** 页数改变 */
const sizeChange = size => {
  details.page.size = size;
  details.page.current = 1;
  initLineData();
};

/** 页码改变 */
const currentChange = current => {
  details.page.current = current;
  initLineData();
};

/** 城市改变 */
const handleChangeCity = (CascaderValue: any[] | null, type: 'start' | 'end') => {
  console.log('CascaderValue :>> ', CascaderValue);

  // 赋值
  switch (type) {
    case 'start':
      if (!CascaderValue) {
        details.form.startProvinceId = ''; // 省
        details.form.startCityId = ''; // 市
        details.form.startCountyId = ''; // 区
      }

      if (CascaderValue.length === 1) {
        details.form.startProvinceId = CascaderValue[0]; // 省
        details.form.startCityId = CascaderValue[0]; // 市
        details.form.startCountyId = CascaderValue[0]; // 区
      } else if (CascaderValue.length === 2) {
        details.form.startProvinceId = CascaderValue[0]; // 省
        details.form.startCityId = CascaderValue[0]; // 市
        details.form.startCountyId = CascaderValue[1]; // 区
      } else {
        details.form.startProvinceId = CascaderValue[0]; // 省
        details.form.startCityId = CascaderValue[1]; // 市
        details.form.startCountyId = CascaderValue[2]; // 区
      }
      break;

    case 'end':
      if (!CascaderValue) {
        details.form.endProvinceId = ''; // 省
        details.form.endCityId = ''; // 市
        details.form.startCountyId = ''; // 区
      }

      if (CascaderValue.length === 1) {
        details.form.endProvinceId = CascaderValue[0]; // 省
        details.form.endCityId = CascaderValue[0]; // 市
        details.form.endCountyId = CascaderValue[0]; // 区
      } else if (CascaderValue.length === 2) {
        details.form.endProvinceId = CascaderValue[0]; // 省
        details.form.endCityId = CascaderValue[0]; // 市
        details.form.endCountyId = CascaderValue[1]; // 区
      } else {
        details.form.endProvinceId = CascaderValue[0]; // 省
        details.form.endCityId = CascaderValue[1]; // 市
        details.form.endCountyId = CascaderValue[2]; // 区
      }
      break;

    default:
      break;
  }
};

/** 新增提货路径 */
const handleAdd = () => {
  handleVehicleTypeStatus();

  details.lineType = 'add';

  details.VehicleBillingDetal = [
    {
      /** 车型 */
      vehicleType: '',
      /** 车型计费(元/车) */
      price: 0,
    },
  ];
  details.form = deepClone(details.initForm);
  console.log(details.initForm, 'details.form');

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

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

      item.price = 0;
    }
  }

  details.form.minCost = 0;
  details.form.additionalCost = 0;

  details.popUpShow.addVsitied = true;
};

/** 给form赋值 */
const initAssignmentForm = (data, isLine = true) => {
  details.form.startCity = [];
  details.form.endCity = [];
  if (isLine) {
    data.startProvinceId && (details.form.startCity[0] = data.startProvinceId + '');
    data.startCityId && (details.form.startCity[1] = data.startCityId + '');
    data.startCountyId && (details.form.startCity[2] = data.startCountyId + '');

    data.endProvinceId && (details.form.endCity[0] = data.endProvinceId + '');
    data.endCityId && (details.form.endCity[1] = data.endCityId + '');
    data.endCountyId && (details.form.endCity[2] = data.endCountyId + '');

    details.form.sendOrgId = data.sendOrgId;
    details.form.sendOrg = data.sendOrgName;
    details.form.priceId = data.priceId;
  }
  // details.form.startCity = [];
  // details.form.endCity = [];
  details.form.minCost = data.minCost || 0;
  details.form.additionalCost = data.additionalCost || 0;

  // 车辆赋值
  details.VehicleBillingDetal = data.fullVehicle || [
    {
      /** 车型 */
      vehicleType: '',
      /** 车型计费(元/车) */
      price: 0,
    },
  ];

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

    value.vehicleType += '';
  }

  const _billTemplateDetailArr = [];

  // 品类赋值
  for (let i = 0; i < details.form.billTemplateDetail.length; i++) {
    const value = details.form.billTemplateDetail[i];
    const _itemObj = {
      title: value.dictValue + '计费品类',
      code: value.dictKey,
      categories: [
        {
          title: '',
          categoryId: '',
          goods: '',
          price: 0,
        },
      ],
    };

    const _arr = [];

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

      const Arr =
        value.code === '1'
          ? // 按件
            data.pieceCategory
          : value.code === '3'
          ? // 按方
            data.cubeCategory
          : // 按重量
            data.weightCategory;
      if (!Arr || Arr.length === 0) break;

      if (Arr.length === 1 && !Arr[0].categoryId) {
        value.categories[0].price = Arr[0].price;
        continue;
      }

      for (let index = 0; index < Arr.length; index++) {
        const val = Arr[index];
        if (val.categoryId !== item.categoryId) continue;
        item.price = val.price;
      }
    }
  }
};

/** 编辑提货路径 */
const handleEdit = async ({ row }) => {
  try {
    details.loadingObj.pageLoading = true;
    details.form = deepClone(details.initForm);

    handleVehicleTypeStatus();

    details.lineType = 'edit';
    details.VehicleBillingDetal = [
      {
        /** 车型 */
        vehicleType: '',
        /** 车型计费(元/车) */
        price: 0,
      },
    ];

    const res = await getDetails(row.id);

    const { code, data } = res.data;
    if (code !== 200) return;

    initAssignmentForm(data);
    details.form.id = row.id;

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

    details.popUpShow.addVsitied = true;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.pageLoading = false;
  }
};

/** 查询收货单位 */
const remoteMethod = async value => {
  try {
    if (!value) return;
    details.loadingObj.loading = true;

    const response = await getList(1, 10, { clientName: value });

    const { code, data } = response.data;

    if (code !== 200) return;

    details.sendOrgArr = data.records || [];
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.loading = false;
  }
};

/** 恢复车辆选择状态 */
const handleVehicleTypeStatus = () => {
  for (let i = 0; i < details.vehicleTypeArr.length; i++) {
    const value = details.vehicleTypeArr[i];
    value.isCheck = 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 () => {
  let isRetrun = false;

  await formRef.value.validate(valid => {
    // if (!valid) return;
    isRetrun = !valid;
  });

  if (isRetrun) return;

  const submitData: any = {
    checkType: '1',
    id: $route.query.id,
    pickup: {},
  };

  // 是否最低计费
  if (details.form.pickupIsMinCost === '1') {
    submitData.pickup.minCost = details.form.minCost;
    submitData.pickup.additionalCost = details.form.additionalCost;
  }

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

    if (!details.form.pickupPricingType.includes(item.code)) continue;

    // 按件
    if (item.code === '1') submitData.pickup.pieceCategory = item.categories;
    // 按方
    else if (item.code === '3') submitData.pickup.cubeCategory = item.categories;
    // 按重量
    else if (item.code === '4') submitData.pickup.weightCategory = item.categories;
  }

  // 按整车
  if (details.form.pickupPricingType.includes('2')) {
    for (let i = 0; i < details.VehicleBillingDetal.length; i++) {
      const value = details.VehicleBillingDetal[i];

      if (!value.vehicleType) return ElMessage.warning('存在未选车型, 请选择车型');
    }

    submitData.pickup.fullVehicle = details.VehicleBillingDetal;
  }

  ElMessageBox.confirm('确认提交', '', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'success',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;

      const res = await putBasicdataPrice(submitData);

      const { code, msg } = res.data;

      if (code !== 200) return;

      ElMessage.success(msg);
      console.log('submitData :>> ', submitData);
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};

/** 提货线路提交 */
const handleSubmitLine = async () => {
  let isRetrun = false;

  await lineFormRef.value.validate(valid => {
    // if (!valid) return;
    isRetrun = !valid;
  });

  if (isRetrun) return;

  const submitData: any = {
    startProvinceId: details.form.startCity[0], // 省
    startCityId: details.form.startCity[1], // 市
    startCountyId: details.form.startCity[2], // 区,
    endProvinceId: details.form.endCity[0], // 省
    endCityId: details.form.endCity[1], // 市
    endCountyId: details.form.endCity[2], // 区,
    /** 提货 */
    serviceType: '1',
    priceId: $route.query.id,
    sendOrgId: details.form.sendOrgId,
  };

  if (details.form.startCity.length <= 1 || details.form.endCity.length <= 1)
    return ElMessage.warning('地址请选择到市一级');

  // if (!submitData.startCountyId) delete submitData.startCountyId;
  // if (!submitData.endCountyId) delete submitData.endCountyId;

  // 如果为编辑提交
  if (details.lineType === 'edit') submitData.id = details.form.id;

  // 是否最低计费
  if (details.form.pickupIsMinCost === '1') {
    submitData.minCost = details.form.minCost;
    submitData.additionalCost = details.form.additionalCost;
  }

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

    if (!details.form.pickupPricingType.includes(item.code)) continue;

    // 按件
    if (item.code === '1') submitData.pieceCategory = item.categories;
    // 按方
    else if (item.code === '3') submitData.cubeCategory = item.categories;
    // 按重量
    else if (item.code === '4') submitData.weightCategory = item.categories;
  }

  // 按整车
  if (details.form.pickupPricingType.includes('2')) {
    for (let i = 0; i < details.VehicleBillingDetal.length; i++) {
      const value = details.VehicleBillingDetal[i];

      if (!value.vehicleType) return ElMessage.warning('存在未选车型, 请选择车型');
    }

    submitData.fullVehicle = details.VehicleBillingDetal;
  }

  ElMessageBox.confirm('确认提交', '', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'success',
  }).then(async () => {
    try {
      details.popUpShow.addVsitied = false; // 关闭弹窗
      details.loadingObj.pageLoading = true; // 开启loading

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

      const res = await postSubmit(submitData);

      const { code, msg } = res.data;

      if (code !== 200) return;

      ElMessage.success(msg);

      handleVehicleTypeStatus();

      initLineData();
      console.log('submitData :>> ', submitData);
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};

/** 删除路径 */
const handleRemoveLine = ({ row }) => {
  ElMessageBox.confirm(`确认删除 【${row.startCountyName}】-【${row.endCountyName}】 数据`, '', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;

      const res = await postRemove({ ids: row.id });
      const { code, msg } = res.data;
      if (code !== 200) return;
      ElMessage.success(msg);

      initLineData();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};

defineExpose({ initDictionaryBiz });
</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 {
    width: 240px;
    font-weight: 600;
    color: #606266;
  }
  .el_table_td {
    display: flex;
    height: 40px;
    align-items: center;
    border-bottom: 1px solid #ccc;
    position: relative;
  }
  .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;
  }
}

.button_container {
  height: 40px;
  position: relative;
}

.title {
  font-size: 1rem;
  font-weight: bold;
  color: var(--el-color-primary);
  margin-bottom: 10px;
}

.table {
  text-align: center;
  border-color: #e8e8e8;
  font-size: 12px;
  line-height: 17px;
  font-weight: bold;

  td,
  th {
    padding: 5px 10px;
    box-sizing: border-box;
  }

  th.index {
    width: fit-content;
    padding: 0 20px;
  }

  td.index {
    font-size: 14px;
  }

  th {
    height: 32px;
  }

  .header {
    background: #f5f8fa;
  }
}

:deep(.el-divider__text.is-left) {
  font-size: 1.04167vw;
  font-weight: bold;
  color: #d3832a;
}

// 新增按钮
.addButton {
  background: #0086f1;
  border-color: #0086f1;
  color: #fff !important;
  cursor: pointer;

  &:hover {
    background: #79bbff;
    border-color: #79bbff;
  }
}

// 移除按钮
.removeButton {
  background: #f85b52;
  border-color: #f85b52;
  color: #fff !important;
  cursor: pointer;

  &:hover {
    background: #f89898;
    border-color: #f89898;
  }
}

.w100 {
  width: 100% !important;
}

:deep(.button.el-text) {
  color: #d3832a !important;
  font-weight: normal;
  cursor: pointer;
  margin-right: 15px;

  &.remove {
    color: #f85b52 !important;
  }
}

.billTemplateDetail_container {
  display: flex;
  flex-wrap: wrap;

  & > div {
    margin-right: 20px;
  }
}

.dialog-footer {
  text-align: end;
}
</style>
