<template>
  <div class="distributionDetailIdx">
    <s-header :name="title" :noback="false"></s-header>
    <van-form show-error-message @submit="onSubmit">
      <div class="cust_vantBorder">
        <div class="kBordBott">
          <template v-if="clientId">
            <van-field disabled colon :border="false" v-model="cofficentForm.clientId" clearable label-width="110"
              name="clientId" :label="$t('distributionSet.addDist.clientId')"
              :placeholder="$t('distributionSet.addDist.autoBrought')" />
          </template>
          <template v-else>
            <van-field colon :border="false" required @click-input="busiInpClk" readonly clearable label-width="110"
              v-model="cofficentForm.clientId" :placeholder="$t('distributionSet.addDist.clientIdPlace')"
              :label="$t('distributionSet.addDist.clientId')" name="clientId"
              :rules="[{ required: true, message: $t('distributionSet.addDist.clientIdPlace') }]">
              <template #right-icon>
                <div class="l-flex-RC">
                  <van-icon v-if="cofficentForm.clientId" @click="cofficentForm.clientId = ''" class="o-mr-6"
                    name="clear" />
                  <van-icon @click="busiInpClk" name="arrow-down" />
                </div>
              </template>
            </van-field>
          </template>
          <div class="l-flex-RC o-p-5 c-text-13 c-text-b">
            <div style="padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);">
              {{ $t('distributionSet.addDist.distInof') }}
            </div>
            <!-- <div class="c-text-13 c-text-b" style="color: #A8A8C5;">{{ $t('distributionSet.addDist.distInof') }}
            </div> -->
          </div>
          <div class="noPaddingTopCell l-flex-RC">
            <van-field type="digit" colon :border="false" required v-model="cofficentForm.distProp" clearable
              label-width="110" name="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'] }]" />
            <span class="o-pl-10 c-text-18 c-text-b" style="color: #434D74;">%</span>
          </div>
          <div class="l-flex-RC">
            <div class="c-text-14" style="padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);">
              &nbsp;&nbsp;{{ $t('distributionSet.addDist.myDistProport') }}：
            </div>
            <div class="c-text-13 c-text-b c-text-color">{{ myDistProp }}%</div>
          </div>
        </div>
        <div v-for="(item, index) in distPropList" :key="index" class="kBordBott">
          <van-field colon :border="false" required v-model="item.name1" clearable label-width="110" name="name1"
            :label="$t('device.accountNoOfDistributorLabel')"
            :placeholder="$t('device.accountNoOfDistributorPlaceholder')"
            :rules="[{ required: true, message: $t('device.accountNoOfDistributorPlaceholder') }]" />
          <div class="l-flex-between noPaddingRCell">
            <div class="l-flex-RC">
              <van-field type="digit" colon :border="false" required v-model="item.name2" clearable label-width="110"
                name="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'] }]" />
              <span class="o-pl-10 c-text-18 c-text-b" style="color: #434D74;">%</span>
            </div>
            <div @click="toDele(index)" class="l-flex-RC" style="color: #FE5D55;">
              <van-icon size="18" name="delete-o" />
              <span class="c-text-12">{{ $t('device.delete') }}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="distPropList.length <= 2" @click="toAdd" class="kBordBott l-flex-center o-ptb-20 c-text-14 c-text-w6">
        +{{ $t('device.continueToAddDistributors') }}
      </div>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          {{ $t('device.submitForApproval') }}
        </van-button>
      </div>
    </van-form>
    <!-- 设备编码选择框 -->
    <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 } from "@/service/distributionSet";
import { saveProportion, getProportion } from '@/service/device';
import sHeader from "@/components/SimpleHeader";
import { showToast } from 'vant';
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 { styleUrl } from '../../common/js/utils';
export default {
  components: { sHeader },
  setup() {
    const route = useRoute();
    // 定义设备id，如果路由中有，那就是设备编辑里面进来的
    const clientId = ref('');
    onMounted(() => {
      // 加载样式
      styleUrl('distributionSet');

      clientId.value = route.query.clientId || '';
      const id = route.query.id || '';
      const type = route.query.type || '';
      cofficentForm.clientId = clientId.value;
      // 如果没有携带编码进来，那就请求接口让用户选择机器编码
      if (!clientId.value) {
        getDeviceListFun();
      } else {
        if (id) {
          // 如果是从分销列表进来的
          getProportionFun(1, id, type);
        } else {
          // 如果设备操作里进来的
          getProportionFun(2, clientId.value);
        }
      }
    });
    // 获取分销详情填充信息
    // 获取分销信息填充
    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 });
      }
      console.log('res', res)
      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;
        }
        console.log('distPropList1111', distPropList)
      }
    }
    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;
      }
      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(res.data.data);
          setTimeout(() => {
            router.back();
          }, 1000);
        }
      })
    };
    // 点击添加分销人
    const toAdd = () => {
      distPropList.push({
        name1: '',
        name2: ''
      })
    }
    // 点击删除
    const toDele = (idx) => {
      if (distPropList.length === 1) {
        showToast(t('distributionSet.addDist.distPropRange'));
        return;
      }
      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') {
        // deviceList.value = data.data.map(item => {
        //     return {name:item.name,clientId}
        // });
        busiPopList.value = data.data.map(item => {
          return { name: item.name != null ? item.name : item.clientId, clientId: item.clientId }
        });
        console.log(busiPopList.value);
      }
    }
    // 设备编码选择框
    const busiPopShow = ref(false);
    const busiPopList = ref([]);
    const busiPopFieldName = reactive({
      text: "name",
      value: "clientId",
    });
    const busiInpClk = () => {
      busiPopShow.value = true;
    };
    // 点击确定按钮
    const busiPopConfirm = ({ selectedOptions }) => {
      console.log(selectedOptions[0]);
      busiPopShow.value = false;
      cofficentForm.clientId = selectedOptions[0].clientId;

      // 重新获取当前设备的分销情况
      getProportionFun(2, selectedOptions[0].clientId);
    };
    const busiPopCancel = () => {
      busiPopShow.value = false;
    };
    return {
      onSubmit,
      cofficentForm,
      toAdd,
      distPropList,
      toDele,
      myDistProp,
      distPropVali,
      title,
      busiPopShow,
      busiPopList,
      busiPopFieldName,
      busiInpClk,
      busiPopConfirm,
      busiPopCancel,
      clientId,
    };
  }
}
</script>

<style lang="less" scoped></style>