<template>
  <view class="commission-form-page">
    <u-navbar
      placeholder
      :autoBack="true"
      :title="pageTitle"
      @rightClick="submitForm"
    >
      <view class="u-nav-slot" slot="right"> 保存 </view>
    </u-navbar>

    <!-- 表单内容 -->
    <view class="follow_form_wrap">
      <u--form
          labelPosition="left"
          labelWidth="130"
          :model="commissionForm"
          :rules="rules"
          ref="commissionFormRef"
          class="form_wrap"
          :errorType="'toast'"
        >
        <u-form-item label="账户类型" prop="accountType" borderBottom :required="true">
          <ld-select
            :list="accountTypeOptions"
            label-key="label"
            value-key="value"
            placeholder="请选择账户类型"
            v-model="commissionForm.accountType"
            :border="false"
          ></ld-select>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="分成人" prop="userName" borderBottom :required="true" @click="handleShowCommissionUser">
          <u--input
            v-model="commissionForm.userName"
            disabled style='pointer-events: none !important'
            disabledColor="#ffffff"
            placeholder="点击选择"
            border="none"
          ></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="分成比例(%)" prop="commissionRate" borderBottom :required="true">
          <u--input
            v-model.number="commissionForm.commissionRate"
            type="number"
            placeholder="请输入分成比例(0-100)"
            border="none"
            @blur="validateCommissionRate"
          ></u--input>
        </u-form-item>

        <u-form-item label="是否归属公司业绩" prop="isCompanyPerformance" borderBottom :required="true">
          <ld-select
            :list="companyPerformanceOptions"
            label-key="label"
            value-key="value"
            placeholder="请选择是否归属公司业绩"
            v-model="commissionForm.isCompanyPerformance"
            :border="false"
          ></ld-select>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="关联收单信息" prop="receiptFormId" borderBottom :required="true">
          <ld-select
            :list="receiptList"
            label-key="item"
            value-key="id"
            placeholder="请选择收单信息"
            v-model="commissionForm.receiptFormId"
            :border="false"
          ></ld-select>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
      </u--form>
    </view>

    <!-- 分成人选择器 -->
    <ba-tree-picker :selectParent="false" v-if="commissionUserList.length > 0" ref="commissionUser" :multiple='false'
      @select-change="commissionUserSelectChange" border title="分成人" :localdata="commissionUserList" valueKey="id" textKey="label"
      childrenKey="children" :selectedValues="commissionForm.userId" :personNames="commissionForm.userName" />
  </view>
</template>

<script>
import ldSelect from "@/components/ld-select/ld-select.vue";
import { filterCustomerManager, handleTree } from '@/utils/util';

export default {
  name: "CommissionForm",
  components: {
    ldSelect
  },
  data() {
    return {
      loading: false,
      commissionForm: {
        id: undefined,
        sendFormId: '',
        clueId: '',
        receiptFormId: '',
        accountType: '1',
        userName: '',
        userId: '',
        commissionRate: undefined,
        isCompanyPerformance: '1'
      },
      receiptList: [],
      commissionUserList: [],
      accountTypeOptions: [
        { label: "前端", value: "1" },
        { label: "后端", value: "2" }
      ],
      companyPerformanceOptions: [
        { label: "是", value: "1" },
        { label: "否", value: "2" }
      ],
      // 表单验证规则
      rules: {
        accountType: [{ required: true, message: "请选择账户类型", trigger: "change" }],
        userName: [{ required: true, message: "请选择分成人", trigger: "blur" }],
        commissionRate: [
          {
            validator: (rule, value, callback) => {
              if (value === undefined || value === null || value === '') {
                callback(new Error("请输入分成比例"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          },
          { type: 'number', min: 0, max: 100, message: '分成比例必须在0-100之间', trigger: "blur" }
        ],
        isCompanyPerformance: [{ required: true, message: "请选择是否归属公司业绩", trigger: "change" }],
        receiptFormId: [{ required: true, message: "请选择关联收单信息", trigger: "change" }]
      },
    };
  },
  computed: {
    pageTitle() {
      return this.commissionForm.id ? "编辑分成" : "新增分成";
    },
  },
  onLoad(options) {
    // 从路由参数获取sendFormId和clueId
    this.commissionForm.sendFormId = options.sendFormId;
    this.commissionForm.clueId = options.clueId;
    this.commissionForm.id = options.id;
    
    // 获取分成人列表
    this.getCommissionUserList();
    
    this.fetchReceiptList().then(() => {
      if (options.id) {
        this.initForm(options.id);
      }
    });
  },
  methods: {
    // 获取分成人列表
    getCommissionUserList() {
      // 获取人员列表
      uni.$u.api.getCustomerManagerAllList().then(res => {
        this.commissionUserList = filterCustomerManager(res.data);
      });
    },
    // 显示分成人选择器
    handleShowCommissionUser() {
      this.$refs.commissionUser._show();
    },
    // 分成人选择变化
    commissionUserSelectChange(ids, names) {
      this.commissionForm.userId = ids[0];
      this.commissionForm.userName = names[0];
    },
    // 获取收单列表
    async fetchReceiptList() {
      try {
        const res = await uni.$u.api.clueReceiptFormListByOrderId(this.commissionForm.sendFormId);
        this.receiptList = res.data || [];
      } catch (error) {
        console.error("获取收单列表失败:", error);
        uni.$u.toast("获取收单列表失败");
      }
    },
    // 初始化表单数据
    async initForm(id) {
      try {
        const res = await uni.$u.api.clueCommissionById(id);
        this.commissionForm = res.data;
      } catch (error) {
        console.error("获取分成详情失败:", error);
        uni.$u.toast("获取分成详情失败");
      }
    },
    // 分成比例验证
    validateCommissionRate() {
      const { commissionRate } = this.commissionForm;
      if (!commissionRate && commissionRate !== 0) return;
      
      const rate = Number(commissionRate);
      if (rate < 0) {
        uni.$u.toast("分成比例不能小于0");
        this.commissionForm.commissionRate = 0;
      } else if (rate > 100) {
        uni.$u.toast("分成比例不能大于100");
        this.commissionForm.commissionRate = 100;
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.commissionFormRef.validate().then(async (valid) => {
        if (valid) {
          await this.handleUpdate();
        } else {
          uni.$u.toast("请检查表单填写是否正确");
        }
      });
    },
    // 更新表单
    async handleUpdate() {
      try {
        this.loading = true;

        // 根据是否有id判断是新增还是修改
        if (this.commissionForm.id) {
          // 修改
          await uni.$u.api.clueCommissionUpdate(this.commissionForm);
		  uni.$emit('addCommissionSuccess');
          uni.$u.toast("修改成功");
        } else {
          // 新增
          await uni.$u.api.clueCommissionAdd(this.commissionForm);
		  uni.$emit('addCommissionSuccess');
          uni.$u.toast("新增成功");
        }

        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        uni.$u.toast(error);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style lang="scss">
.commission-form-page {
  background-color: #fff;
}
@import "@/static/follow/index.scss";
</style>