<template>
  <el-main class="config-commission">
    <el-form ref="formRef" :model="form.model" :rules="form.rules" label-width="122px">
      <el-alert class="sa-m-b-16">
        <template #title>
          设置分销时，请先了解
          <a
            class="shopro-form-group-title-href"
            href="https://www.spp.gov.cn/flfg/gfwj/201311/t20131122_64638.shtml"
            target="_blank"
            rel="noopener noreferrer"
            >《关于办理组织领导传销活动刑事案件适用法律若干问题的意见》</a
          >
        </template>
      </el-alert>
      <div class="sa-title sa-title--line sa-m-b-16">分销设置</div>
      <el-form-item label="分销层级">
        <div>
          <el-radio-group v-model="form.model.level">
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="1">一级</el-radio>
            <el-radio :label="2">二级</el-radio>
            <el-radio :label="3">三级</el-radio>
          </el-radio-group>
          <div class="tip">默认佣金比例请到 分销商等级 进行设置</div>
        </div>
      </el-form-item>
      <el-form-item label="分销自购">
        <div>
          <el-radio-group v-model="form.model.self_buy">
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="1">开启</el-radio>
          </el-radio-group>
          <div class="tip"> 自购优惠开启后，分销商自己购买时，下单可以给自己返佣 </div>
        </div>
      </el-form-item>
      <el-form-item label="锁定下级条件">
        <div>
          <el-radio-group v-model="form.model.invite_lock">
            <el-radio label="share">首次通过分享进入</el-radio>
            <el-radio label="pay" :disabled="form.model.become_agent.type === 'user'"
              >首次付款</el-radio
            >
            <el-radio label="agent" :disabled="form.model.become_agent.type === 'user'"
              >成为子分销商</el-radio
            >
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item label="分销商审核">
        <el-radio-group v-model="form.model.agent_check">
          <el-radio :label="0">不需要</el-radio>
          <el-radio :label="1">需要</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="越级升级">
        <el-radio-group v-model="form.model.upgrade_jump">
          <el-radio :label="0">不允许</el-radio>
          <el-radio :label="1">允许</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="升级审核">
        <el-radio-group v-model="form.model.upgrade_check">
          <el-radio :label="0">自动升级</el-radio>
          <el-radio :label="1">审核后升级</el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="sa-title sa-title--line sa-m-b-16">分销商设置</div>
      <!-- <el-form-item label="分销中心背景图" prop="background_image">
        <sa-uploader v-model="form.model.background_image" fileType="image"></sa-uploader>
      </el-form-item> -->
      <template v-if="form.model.become_agent">
        <el-form-item label="成为分销商条件">
          <div>
            <el-radio-group v-model="form.model.become_agent.type" @change="onChangeBecomeAgentType"
              ><el-radio label="user">新会员注册</el-radio>
              <el-radio label="apply">自助申请</el-radio>
              <el-radio label="goods">购买任意商品</el-radio>
              <el-radio label="consume">消费累计</el-radio>
            </el-radio-group>
            <div v-if="form.model.become_agent.type == 'user'" class="tip">
              新会员注册后将直接成为分销商,锁定下级条件会自动设置为[首次通过分享进入]
            </div>
            <div v-if="form.model.become_agent.type == 'apply'" class="tip">
              会员必须进入分销中心手动完善资料并提交后可成为分销商
            </div>
            <div v-if="form.model.become_agent.type == 'goods'" class="tip">
              会员必须购买下方选定的任意其中一款商品可成为分销商
            </div>
            <div v-if="form.model.become_agent.type == 'consume'" class="tip">
              会员在商城的总计消费达到设定的金额后可成为分销商
            </div>
          </div>
        </el-form-item>
        <template v-if="form.model.become_agent.type == 'goods'">
          <el-form-item>
            <el-button class="is-link" type="primary" @click="selectGoods">+ 添加商品</el-button>
          </el-form-item>
          <el-form-item v-if="tempGoods.list.length > 0">
            <div class="sa-template-content sa-template-goods">
              <div class="header sa-flex">
                <div class="item">商品信息</div>
                <div class="oper">操作</div>
              </div>
              <div class="list sa-flex" v-for="(gl, gidx) in tempGoods.list" :key="gl">
                <div class="item sa-flex">
                  <sa-image :url="gl.image" size="40"></sa-image>
                  <div class="sa-m-l-8">
                    <div class="title">{{ gl.title }}</div>
                    <div class="price">¥{{ gl.price.join('~') }}</div>
                  </div>
                </div>
                <div class="oper">
                  <el-button class="is-link" type="danger" @click="deleteGoods(gidx)"
                    >移除</el-button
                  >
                </div>
              </div>
            </div>
          </el-form-item>
        </template>
        <el-form-item v-if="form.model.become_agent.type == 'consume'">
          <el-input v-model="form.model.become_agent.value">
            <template #append>元</template>
          </el-input>
        </el-form-item>
      </template>
      <template v-if="form.model.become_agent.type != 'user'">
        <template v-if="form.model.agent_form">
          <el-form-item label="完善资料">
            <el-radio-group v-model="form.model.agent_form.status">
              <el-radio label="0" :disabled="form.model.become_agent.type == 'apply'"
                >不需要</el-radio
              >
              <el-radio label="1">需要</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="form.model.agent_form.status == '1'">
            <el-form-item label="表单背景图" prop="agent_form.background_image">
              <sa-uploader
                v-model="form.model.agent_form.background_image"
                fileType="image"
              ></sa-uploader>
            </el-form-item>
            <el-form-item label="表单内容">
              <div class="sa-template-content sa-template-form">
                <div class="header sa-flex">
                  <div class="item">表单类型</div>
                  <div class="item">表单名称</div>
                  <div class="oper">操作</div>
                </div>
                <sa-draggable
                  v-model="form.model.agent_form.content"
                  :animation="300"
                  handle=".sortable-drag"
                  item-key="element"
                >
                  <template #item="{ element, index }">
                    <div class="list sa-flex">
                      <el-form-item
                        class="item"
                        :prop="`agent_form.content.${index}.type`"
                        :rules="form.rules.agent_form.content.type"
                      >
                        <el-select v-model="element.type" placeholder="表单类型">
                          <template v-for="br in become_register_options" :key="br">
                            <el-option :label="br.label" :value="br.value" />
                          </template>
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        class="item"
                        :prop="`agent_form.content.${index}.name`"
                        :rules="form.rules.agent_form.content.name"
                      >
                        <el-input v-model="element.name" placeholder="表单名称"></el-input>
                      </el-form-item>
                      <div class="oper">
                        <el-button class="is-link" type="danger" @click="deleteContent(index)"
                          >移除</el-button
                        >
                        <sa-svg class="sa-m-l-8 sortable-drag" name="sa-round"></sa-svg>
                      </div>
                    </div>
                  </template>
                </sa-draggable>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button class="sa-m-l-12" icon="Plus" @click="addContent">追加</el-button>
            </el-form-item>
          </template>
        </template>
        <template v-if="form.model.apply_protocol">
          <el-form-item label="申请协议">
            <el-radio-group v-model="form.model.apply_protocol.status">
              <el-radio label="0">不显示</el-radio>
              <el-radio label="1">显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.model.apply_protocol.status == '1'" label="协议内容">
            <el-input v-model="form.model.apply_protocol.title" placeholder="请选择协议内容">
              <template #append>
                <span class="cursor-pointer" @click="selectRichtext">选择富文本</span>
              </template>
            </el-input>
          </el-form-item>
        </template>
      </template>
      <div class="sa-title sa-title--line sa-m-b-16">结算条件</div>
      <el-form-item label="商品结算方式">
        <div>
          <el-radio-group v-model="form.model.reward_type">
            <el-radio label="goods_price">商品价</el-radio>
            <el-radio label="pay_price">实际支付价</el-radio>
          </el-radio-group>
          <div class="tip"> 商品价: 商品实际售价/规格价，实际支付价: 实际支付的费用(不含运费) </div>
        </div>
      </el-form-item>
      <el-form-item label="佣金结算方式">
        <el-radio-group v-model="form.model.reward_event">
          <el-radio label="paid">支付后结算</el-radio>
          <el-radio label="confirm">确认收货结算</el-radio>
          <el-radio label="finish">订单完成结算</el-radio>
          <el-radio label="admin">手动打款</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分销佣金">
        <el-radio-group v-model="form.model.refund_commission_reward">
          <el-radio :label="0">退款不扣除</el-radio>
          <el-radio :label="1">退款扣除</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分销业绩">
        <el-radio-group v-model="form.model.refund_commission_order">
          <el-radio :label="0">退款不扣除</el-radio>
          <el-radio :label="1">退款扣除</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </el-main>
  <el-footer class="sa-footer--submit">
    <el-button @click="getConfig">重置</el-button>
    <el-button type="primary" @click="onSave">保存</el-button>
  </el-footer>
  <el-dialog
    class="configis-upgrade-dialog"
    :close-on-click-modal="false"
    width="900px"
    v-model="state.configis_upgrade"
  >
    <div class="configis-upgrade-image">
      <img src="/static/images/shop/config/upgrade-config.png" />
      <div class="configis-upgrade-close" @click="onOper('close')">
        <el-icon><circle-close-filled /></el-icon>
      </div>
      <div class="configis-upgrade-button sa-flex">
        <div class="configis-upgrade-button-refresh sa-flex" @click="onOper('refresh')">
          <el-icon class="refresh-right">
            <refresh-right />
          </el-icon>
          刷新
        </div>
        <div class="configis-upgrade-button-upgrade sa-flex" @click="onOper('upgrade')"
          >去升级
          <img class="icon-right" src="/static/images/shop/config/icon-right.png" />
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import SaDraggable from 'vuedraggable';
  import { api } from '../config.service';
  import adminApi from '@/app/admin/api';
  import { api as goodsApi } from '@/app/shop/admin/goods/goods.service';
  import { useModal } from '@/sheep/hooks';
  import RichtextSelect from '@/app/shop/admin/data/richtext/select.vue';
  import GoodsSelect from '@/app/shop/admin/goods/goods/select.vue';

  const formRef = ref();
  const form = reactive({
    model: {
      level: 0,
      self_buy: 0,
      invite_lock: 'share',
      agent_check: 0,
      upgrade_jump: 0,
      upgrade_check: 0,
      become_agent: {
        type: 'apply',
        value: '',
      },
      // background_image: '',
      agent_form: {
        status: '0',
        background_image: '',
        content: [
          {
            type: '',
            name: '',
          },
        ],
      },
      apply_protocol: {
        status: '0',
        id: '',
        title: '',
      },
      reward_type: 'goods_price',
      reward_event: 'paid',
      refund_commission_reward: 0,
      refund_commission_order: 0,
    },
    rules: {
      // background_image: [{ required: true, message: '请选择分销中心背景图', trigger: 'blur' }],
      agent_form: {
        background_image: [{ required: true, message: '请选择表单背景图', trigger: 'blur' }],
        content: {
          type: [{ required: true, message: '表单类型', trigger: 'change' }],
          name: [{ required: true, message: '表单名称', trigger: 'blur' }],
        },
      },
    },
  });
  const state = reactive({
    configis_upgrade: false,
  });

  function onChangeBecomeAgentType(type) {
    if (type === 'apply') {
      form.model.agent_form.status = '1';
    }
    if (type === 'user') {
      form.model.invite_lock = 'share';
    }
    form.model.become_agent.value = '';
  }

  function selectRichtext() {
    useModal(
      RichtextSelect,
      {
        title: '选择活动说明',
      },
      {
        confirm: (res) => {
          form.model.apply_protocol.id = res.data.id;
          form.model.apply_protocol.title = res.data.title;
        },
      },
    );
  }

  const tempGoods = reactive({
    list: [],
  });

  async function getGoodsList(ids) {
    const { data } = await goodsApi.goods.select(
      {
        search: JSON.stringify({ id: [ids, 'in'] }),
      },
      'select',
    );
    tempGoods.list = data;
  }

  function selectGoods() {
    let ids = [];
    tempGoods.list.forEach((i) => {
      ids.push(i.id);
    });
    useModal(
      GoodsSelect,
      {
        title: '选择商品',
        multiple: true,
        ids,
      },
      {
        confirm: (res) => {
          tempGoods.list = res.data;

          let ids = [];
          tempGoods.list.forEach((gl) => {
            ids.push(gl.id);
          });
          form.model.become_agent.value = ids.join(',');
        },
      },
    );
  }
  function deleteGoods(index) {
    tempGoods.list.splice(index, 1);
    let ids = [];
    tempGoods.list.forEach((gl) => {
      ids.push(gl.id);
    });
    form.model.become_agent.value = ids.join(',');
  }

  const become_register_options = [
    {
      value: 'text',
      label: '文本内容',
    },
    {
      value: 'number',
      label: '纯数字',
    },
    {
      value: 'image',
      label: '上传图片',
    },
  ];
  function addContent() {
    form.model.agent_form.content.push({
      type: '',
      name: '',
    });
  }
  function deleteContent(index) {
    form.model.agent_form.content.splice(index, 1);
  }

  async function getConfig() {
    const { data } = await api.commission();
    form.model = data;
    if (form.model.become_agent.type == 'goods') {
      getGoodsList(form.model.become_agent.value);
    }
    const initData = await adminApi.init();
    if (!initData.data.is_pro) {
      state.configis_upgrade = true;
    }
  }

  function onOper(type) {
    switch (type) {
      case 'close':
        state.configis_upgrade = false;
        break;
      case 'refresh':
        window.location.reload();
        break;
      case 'upgrade':
        window.open('https://shopro.top/buy');
        break;
    }
  }

  function resetFrom() {
    getConfig();
  }

  function onSave() {
    unref(formRef) &&
      unref(formRef).validate(async (valid) => {
        if (valid) {
          await api.commission(form.model);
        }
      });
  }

  onMounted(() => {
    getConfig();
  });
</script>

<style lang="scss">
  .configis-upgrade-dialog {
    .el-dialog__body {
      padding: 0 !important;
    }

    .el-dialog__header {
      height: 0 !important;
      padding: 0 !important;
    }
  }
</style>
<style lang="scss" scoped>
  .config-commission {
    .sa-title {
      font-weight: 500;
      color: var(--sa-title);
    }

    .el-alert {
      --el-alert-bg-color: var(--sa-background-hex-hover);
      color: var(--sa-subtitle);

      :deep() {
        .el-alert__content {
          padding: 0;
        }

        .el-alert__close-btn {
          color: var(--el-color-primary);
        }
      }
    }
  }

  .configis-upgrade-image {
    width: 900px;
    height: 580px;
    background: #ffffff;
    border-radius: 4px;
    position: relative;
  }

  img {
    width: 100%;
    height: 100%;
  }

  .configis-upgrade-button {
    position: absolute;
    bottom: 162px;
    right: 360px;
  }

  .configis-upgrade-button-upgrade {
    width: 110px;
    height: 34px;
    background: #8322ff;
    border-radius: 2px;
    justify-content: center;
    font-weight: bold;
    font-size: 12px;
    color: #ffffff;
    margin-left: 42px;
    cursor: pointer;

    .icon-right {
      margin-left: 12px;
      width: 18px;
      height: 18px;
    }
  }

  .configis-upgrade-button-refresh {
    color: #86818e;
    font-size: 12px;
    cursor: pointer;

    .refresh-right {
      margin-right: 6px;
      font-size: 14px;
    }
  }

  .configis-upgrade-close {
    position: absolute;
    top: 53px;
    right: 58px;
    font-size: 20px;
    color: #7f7a87;
    cursor: pointer;
  }
</style>
