<template>
  <div class="distribution-detail">
    <s-header :name="title" :noback="false" />

    <div class="content-container">
      <!-- 主要内容区域 -->
      <div class="detail-container">
        <!-- 客户ID输入区域 -->
        <div class="input-section">
          <van-icon name="desktop-o" class="icon" />
          <template v-if="clientId">
            <van-field disabled v-model="cofficentForm.clientId" />
          </template>
          <template v-else>
            <van-field
              :border="false"
              required
              readonly
              v-model="cofficentForm.clientId"
              :label="$t('distributionSet.addDist.clientId')"
              :placeholder="$t('distributionSet.addDist.clientIdPlace')"
              :rules="[
                {
                  required: true,
                  message: $t('distributionSet.addDist.clientIdPlace'),
                },
              ]"
              @click-input="busiInpClk"
            >
              <template #right-icon>
                <div class="field-icons">
                  <van-icon
                    v-if="cofficentForm.clientId"
                    @click.stop="cofficentForm.clientId = ''"
                    name="clear"
                  />
                  <van-icon @click.stop="busiInpClk" name="arrow-down" />
                </div>
              </template>
            </van-field>
          </template>
        </div>

        <!-- 信息展示区域 -->
        <div class="info-section">
          <div class="section-title">
            <van-icon name="todo-list-o" size="22" class="section-icon" />
            {{
              proportionCheck
                ? $t("distributionSet.addDist.pendingRecord")
                : $t("distributionSet.addDist.distInof")
            }}
          </div>

          <!-- 比例展示模式 -->
          <template v-if="proportionCheck">
            <div class="distributor-group">
              <div class="proportion-row">
                <span>{{
                  $t("device.proportionOfPlatformDistributionLabel")
                }}</span>
                <span class="percentage"
                  >{{ proportionCheck.adminProportion }}%</span
                >
              </div>
              <div class="proportion-row">
                <span>{{ $t("distributionSet.addDist.myDistProport") }}</span>
                <span class="percentage"
                  >{{ proportionCheck.proportion }}%</span
                >
              </div>
            </div>

            <!-- 动态分销商信息 -->
            <div
              v-for="distributor in activeDistributors"
              :key="distributor.type"
              class="distributor-group"
            >
              <div class="distributor-row">
                <span>{{ $t("device.accountNoOfDistributorLabel") }}</span>
                <span class="value">{{ distributor.name }}</span>
              </div>
              <div class="distributor-row">
                <span>{{ $t("device.distributionProportionLabel") }}</span>
                <span class="percentage">{{ distributor.proportion }}%</span>
              </div>
            </div>

            <div class="action-button">
              <van-button
                round
                block
                type="primary"
                @click="cancelDistri(proportionCheck.id)"
              >
                {{ $t("device.cancelForApproval") }}
              </van-button>
            </div>
          </template>

          <!-- 表单编辑模式 -->
          <van-form v-else @submit="onSubmit" class="edit-form">
            <div class="form-group">
              <div class="distributor-input">
                <div class="input-with-unit">
                  <van-field
                    type="digit"
                    clearable
                    required
                    v-model="cofficentForm.distProp"
                    :label="$t('device.proportionOfPlatformDistributionLabel')"
                    :placeholder="
                      $t('device.proportionOfPlatformDistributionPlaceholder')
                    "
                    :rules="[
                      {
                        required: true,
                        message: $t(
                          'device.proportionOfPlatformDistributionPlaceholder'
                        ),
                      },
                      {
                        required: true,
                        validator: distPropVali,
                        message: $t('distributionSet.addDist.platDistRange'),
                        trigger: ['onChange', 'onBlur', 'onSubmit'],
                      },
                    ]"
                  >
                    <template #extra>
                      <span class="unit">%</span>
                    </template>
                  </van-field>
                </div>

                <div class="my-proportion">
                  <span class="label">{{
                    $t("distributionSet.addDist.myDistProport")
                  }}</span>
                  <span class="percentage o-pl-25">{{ myDistProp }} %</span>
                </div>
              </div>

              <!-- 动态分销商输入 -->
              <div
                v-for="(item, index) in distPropList"
                :key="index"
                class="distributor-input"
              >
                <van-field
                  clearable
                  required
                  v-model="item.name1"
                  :label="$t('device.accountNoOfDistributorLabel')"
                  :placeholder="$t('device.accountNoOfDistributorPlaceholder')"
                  :rules="[
                    {
                      required: true,
                      message: $t('device.accountNoOfDistributorPlaceholder'),
                    },
                  ]"
                />

                <div class="proportion-input">
                  <div class="input-with-unit">
                    <van-field
                      type="digit"
                      required
                      clearable
                      v-model="item.name2"
                      :label="$t('device.distributionProportionLabel')"
                      :placeholder="
                        $t('device.distributionProportionPlaceholder')
                      "
                      :rules="[
                        {
                          required: true,
                          message: $t(
                            'device.distributionProportionPlaceholder'
                          ),
                        },
                        {
                          required: true,
                          validator: distPropVali,
                          message: $t('distributionSet.addDist.distPropRange'),
                          trigger: ['onChange', 'onBlur', 'onSubmit'],
                        },
                      ]"
                    >
                      <template #extra>
                        <span class="unit">%</span>
                      </template></van-field
                    >
                  </div>
                  <div class="delete-btn" @click="toDele(index)">
                    <van-icon name="delete-o" size="20" />
                  </div>
                </div>
              </div>

              <div
                v-if="distPropList.length <= 2"
                class="add-button"
                @click="toAdd"
              >
                +{{ $t("device.continueToAddDistributors") }}
              </div>
            </div>

            <div class="action-button">
              <van-button round block type="primary" native-type="submit">
                {{ $t("device.submitForApproval") }}
              </van-button>
            </div>
          </van-form>
        </div>
      </div>
    </div>

    <!-- 设备编码选择弹窗 -->
    <van-popup v-model:show="busiPopShow" position="bottom">
      <van-picker
        :title="$t('distributionSet.addDist.clientIdPlace')"
        :columns="busiPopList"
        :columns-field-names="busiPopFieldName"
        @confirm="busiPopConfirm"
        @cancel="busiPopCancel"
      />
    </van-popup>
  </div>
</template>

<script>
import { getEquipmentList } from "@/service/typeSelectList";
import {
  Api_getDistriDetail,
  Api_getCheckPending,
  Api_cancelDistri,
} from "@/service/distributionSet";
import { saveProportion, getProportion } from "@/service/device";
import sHeader from "@/components/SimpleHeader";
import { computed, onMounted, reactive, ref } from "vue";
import { getLoginUser } from "@/common/js/utils";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import {
  showToast,
  showConfirmDialog,
  showSuccessToast,
  showFailToast,
} from "vant";

export default {
  components: { sHeader },
  setup() {
    const route = useRoute();
    // 定义设备id，如果路由中有，那就是设备编辑里面进来的
    const clientId = ref("");
    // 待审核记录
    const proportionCheck = ref(null);
    const id = route.query.id || "";
    const type = route.query.type || "";
    onMounted(() => {
      // 加载样式
      // styleUrl('distributionSet');

      clientId.value = route.query.clientId || "";
      cofficentForm.clientId = clientId.value;
      // 如果没有携带编码进来，那就请求接口让用户选择机器编码
      if (!clientId.value) {
        getDeviceListFun();
      } else {
        if (id) {
          // 如果是从分销列表进来的
          getProportionFun(1, id, type);
        } else {
          // 如果设备操作里进来的
          getProportionFun(2, clientId.value);
        }
        getCheckPending();
      }
    });
    // 获取分销详情填充信息
    // 获取分销信息填充
    const getProportionFun = async (idx, id, type) => {
      let res = null;
      if (idx === 1) {
        res = await Api_getDistriDetail({ id, type });
      } else {
        res = await getProportion({ adminId: user.id, clientId: id });
      }
      const data = res.data;
      if (data.code === "00000") {
        cofficentForm.clientId = data.data.clientId;
        cofficentForm.distProp = data.data.adminProportion;
        // 存在第一个分销人账号和分销比，填充
        if (data.data.agencyName && data.data.agencyProportion !== "") {
          distPropList[0] = {};
          distPropList[0]["name1"] = data.data.agencyName;
          distPropList[0]["name2"] = data.data.agencyProportion;
        } // 存在第二个分销人账号和分销比，填充
        if (data.data.merchantName && data.data.merchantProportion !== "") {
          distPropList[1] = {};
          distPropList[1]["name1"] = data.data.merchantName;
          distPropList[1]["name2"] = data.data.merchantProportion;
        } // 存在第三个分销人账号和分销比，填充
        if (data.data.personageName && data.data.personageProportion !== "") {
          distPropList[2] = {};
          distPropList[2]["name1"] = data.data.personageName;
          distPropList[2]["name2"] = data.data.personageProportion;
        }
      }
    };
    const { t } = useI18n();
    const title = ref(t("distributionSet.addDist.title"));
    // 获取登陆用户
    const user = getLoginUser();
    const router = useRouter();
    // 提交审批参数
    const cofficentForm = reactive({
      clientId: "",
      distProp: "",
    });
    // 我的分销比例
    const myDistProp = computed(() => {
      // 计算出分销人的总分销
      const totalProp = distPropList.reduce((pre, cur) => {
        return Number(cur.name2 || 0) + pre;
      }, 0);
      return 100 - Number(cofficentForm.distProp || 0) - Number(totalProp);
    });
    // 分销人列表
    const distPropList = reactive([]);
    // 点击提交审批按钮
    const onSubmit = () => {
      if (cofficentForm.distProp == "0") {
        showToast(t("distributionSet.addDist.noZero"));
        return;
      }
      if (distPropList.length > 0) {
        if (distPropList[0] && distPropList[0]["name2"] == "0") {
          showToast(t("distributionSet.addDist.zeroDis"));
          return;
        }
        if (distPropList[1] && distPropList[1]["name2"] == "0") {
          showToast(t("distributionSet.addDist.zeroDis"));
          return;
        }
        if (distPropList[2] && distPropList[2]["name2"] == "0") {
          showToast(t("distributionSet.addDist.zeroDis"));
          return;
        }
      }
      let param = {
        adminId: user.id,
        clientId: cofficentForm.clientId,
        type: distPropList.length,
        proportion: myDistProp.value,
        agencyName: distPropList[0] ? distPropList[0]["name1"] : "",
        merchantName: distPropList[1] ? distPropList[1]["name1"] : "",
        personageName: distPropList[2] ? distPropList[2]["name1"] : "",
        agencyProportion: distPropList[0] ? distPropList[0]["name2"] : "",
        merchantProportion: distPropList[1] ? distPropList[1]["name2"] : "",
        personageProportion: distPropList[2] ? distPropList[2]["name2"] : "",
        adminProportion: cofficentForm.distProp,
      };
      saveProportion(param).then((res) => {
        if (res.data.code === "00000") {
          showToast(t("distributionSet.addDist.submitSuccess"));
          setTimeout(() => {
            router.back();
          }, 1000);
        } else if (res.data.code === "B0001") {
          // showToast(t('distributionSet.addDist.hasExamine'));
          showToast(res.data.message);
        } else {
          showToast(t("distributionSet.addDist.submitFailed"));
        }
      });
    };
    // 点击添加分销人
    const toAdd = () => {
      distPropList.push({
        name1: "",
        name2: "",
      });
    };
    // 点击删除
    const toDele = (idx) => {
      distPropList.splice(idx, 1);
    };
    // 分销比例规则
    const distPropVali = (val) => /^(\d{1,2}|100)$/.test(val);
    // 获取设备列表
    const getDeviceListFun = async () => {
      const { data } = await getEquipmentList({ adminId: user.id });
      if (data.code === "00000") {
        busiPopList.value = data.data.map((item) => {
          return {
            name: item.name != null ? item.name : item.clientId,
            clientId: item.clientId,
          };
        });
      }
    };
    // 设备编码选择框
    const busiPopShow = ref(false);
    const busiPopList = ref([]);
    const busiPopFieldName = reactive({
      text: "name",
      value: "clientId",
    });
    const busiInpClk = () => {
      busiPopShow.value = true;
    };
    // 点击确定按钮
    const busiPopConfirm = ({ selectedOptions }) => {
      busiPopShow.value = false;
      cofficentForm.clientId = selectedOptions[0].clientId;

      // 重新获取当前设备的分销情况
      getProportionFun(2, selectedOptions[0].clientId);
      getCheckPending();
    };
    const busiPopCancel = () => {
      busiPopShow.value = false;
    };

    // 获取已提交的审核记录
    const getCheckPending = async () => {
      const { data } = await Api_getCheckPending({
        adminId: user.id,
        clientId: cofficentForm.clientId,
      });
      if (data.code === "00000") {
        // 存在审核记录，则不能再提交
        proportionCheck.value = data.data;
      }
    };

    // 撤销分销申请
    const cancelDistri = (value) => {
      showConfirmDialog({
        title: t("user.tips"),
        message: t("distributionSet.changeTips"),
      })
        .then(async () => {
          const { data } = await Api_cancelDistri({ id: value });
          if (data.code == "00000") {
            showSuccessToast(t("distributionSet.cancelSuccess"));
            setTimeout(() => {
              proportionCheck.value = [];
              if (!clientId.value) {
                getDeviceListFun();
              } else {
                if (id) {
                  // 如果是从分销列表进来的
                  getProportionFun(1, id, type);
                } else {
                  // 如果设备操作里进来的
                  getProportionFun(2, clientId.value);
                }
                getCheckPending();
              }
            }, 1000);
          } else {
            showFailToast(data.message);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    };

    const activeDistributors = computed(() => {
      return [
        {
          type: "agency",
          name: proportionCheck.value.agencyName,
          proportion: proportionCheck.value.agencyProportion,
        },
        {
          type: "merchant",
          name: proportionCheck.value.merchantName,
          proportion: proportionCheck.value.merchantProportion,
        },
        {
          type: "personage",
          name: proportionCheck.value.personageName,
          proportion: proportionCheck.value.personageProportion,
        },
      ].filter((d) => d.name && d.proportion);
    });

    return {
      onSubmit,
      cofficentForm,
      toAdd,
      distPropList,
      toDele,
      myDistProp,
      distPropVali,
      title,
      busiPopShow,
      busiPopList,
      busiPopFieldName,
      busiInpClk,
      busiPopConfirm,
      busiPopCancel,
      clientId,
      proportionCheck,
      cancelDistri,
      activeDistributors,
    };
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4d6add;
@text-color: #29b664;
@text-primary: #434d74;
@border-color: #e4e7ec;
@error-color: #fe5d55;

.distribution-detail {
  background: #f8fafb;
  min-height: 100vh;

  .content-container {
    background: #f5f6fa;
    height: calc(100% - 50px);
    overflow: auto;
    overflow-x: hidden;
  }

  .detail-container {
    margin: 12px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  }
}

.input-section {
  padding: 5px;
  display: flex;
  align-items: center;

  border-bottom: 1px solid @border-color;

  .icon {
    font-size: 18px;
    color: @primary-color;
    margin-right: 10px;
  }

  .field-icons {
    display: flex;
    gap: 8px;
    align-items: center;

    .van-icon {
      color: #999;
      font-size: 18px;

      &:active {
        color: @primary-color;
      }
    }
  }
}

.info-section {
  padding: 16px;

  .section-icon {
    color: @primary-color;
    margin-right: 10px;
  }

  .section-title {
    padding: 12px 0;
    font-weight: 500;
    font-size: 15px;
    color: @text-primary;
    border-bottom: 1px solid @border-color;
    margin-bottom: 16px;
  }
}

// 通用样式
.proportion-row,
.distributor-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;

  .percentage {
    color: @primary-color;
    font-weight: 500;
  }
}

.distributor-group {
  margin: 12px 0;
  padding: 12px;
  background: #f8fafb;
  border-radius: 8px;
}

:deep(.van-field__control) {
  /* 输入框容器样式 */
  border: 1px solid #e4e7ec;
  border-radius: 8px;
  padding: 5px;
  transition: border-color 0.3s;
}

:deep(.van-field) {
  /* 输入框容器样式 */
  padding: 10px 8px;

  /* label文本居中对齐 */
  .van-field__label {
    display: flex;
    align-items: center;
    justify-content: center;
    color: @primary-color;
    font-weight: 500;
    width: 100px;

    /* 小屏幕适配 */
    @media (max-width: 480px) {
      width: 100px;
      font-size: 13px;
    }
  }

  .unit {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.edit-form {
  .input-with-unit {
    display: flex;
    align-items: center;

    .van-field {
      flex: 1;
    }

    .unit {
      color: @text-primary;
      padding-left: 8px;
    }
  }

  .my-proportion {
    padding: 10px 20px;
    color: @text-color;
    font-size: 20px;

    .label {
      font-size: 14px;
    }

    .percentage {
      font-weight: 500;
      font-size: 14px;
    }
  }
}

.distributor-input {
  margin: 10px 0;
  border: 1px solid @border-color;
  border-radius: 8px;
  padding: 12px 0;

  .proportion-input {
    display: flex;
    gap: 5px;
    align-items: center;

    .delete-btn {
      color: @error-color;
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 0 8px;
    }
  }
}

.add-button {
  color: @primary-color;
  text-align: center;
  padding: 12px;
  border: 1px dashed @primary-color;
  border-radius: 8px;
  margin: 16px 0;
  cursor: pointer;
}

.action-button {
  margin: 40px 16px;
}

@media (max-width: 480px) {
  .detail-container {
    border-radius: 8px;
  }

  .input-section,
  .info-section {
    padding: 10px;
  }
}
</style>
