import { reactive } from 'vue';
<template>
  <PageLayout>
    <q-list separator class="bg-white">
      <q-item class="items-start">
        <q-item-section avatar>
          <UserAvatar color="accent" :src="info.avatar_url||info.avatar"></UserAvatar>
        </q-item-section>
        <q-item-section>
          <q-item-label
            >{{ info.remark || info.nickname
            }}<q-btn
              icon="border_color"
              size="sm"
              dense
              flat
              @click="editRemarkName"
          /></q-item-label>
          <q-item-label caption>昵称：{{ info.nickname }}</q-item-label>
          <q-item-label caption
            >电话：<span @click="seePhone = !seePhone"
              >{{ seePhone ? info.phone : "******" }}
              <q-icon :name="!seePhone ? 'remove_red_eye' : 'visibility_off'"
            /></span>
            <q-btn
              size="xs"
              color="grey-7"
              class="q-px-sm q-ml-sm"
              unelevated
              dense
              label="复制"
              @click="safeCopyToClipboard(info.phone)"
          /></q-item-label>
          <q-item-label caption>注册：{{ formatDate(info.created_at) }}</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-btn
            unelevated
            :icon="info.star ? 'star' : 'star_border'"
            :color="info.star ? 'deep-orange-1' : 'grey-2'"
            :text-color="info.star ? 'accent' : 'grey-7'"
            round
            @click="toggleStar(info.star == 1 ? 0 : 1)"
          ></q-btn>
        </q-item-section>
      </q-item>
      <q-item class="items-end q-py-md">
        <q-item-section>
          <q-item-label caption>账户余额（元）</q-item-label>
          <q-item-label class="text-primary text-h5">{{
            formatMoney(info.balance)
          }}</q-item-label>
        </q-item-section>
        <q-item-section side v-if="store.user.enable_ie==1">
          <AuthButton>
          <q-btn-group unelevated>
            <q-btn
              color="yellow"
              text-color="brown-6"
              style="padding-left:12px;padding-right: 12px;"
              @click="moneyDialog = 'recharge'"
              >充值</q-btn
            >
            <q-btn
              color="amber"
              text-color="brown-7"
              style="padding-left:12px;padding-right: 12px;"
              @click="moneyDialog = 'incr'"
              >加款</q-btn
            >
            <q-btn
              color="orange"
              text-color="brown-7"
              style="padding-left:12px;padding-right: 12px;"
              @click="moneyDialog = 'reduce'"
              >扣款</q-btn
            >
          </q-btn-group>
          </AuthButton>
        </q-item-section>
      </q-item>
      <q-item :to="'/customer/' + info.id+'/wallet/bills'">
        <q-item-section>
          <q-item-label>账户明细</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-icon name="arrow_forward_ios" size="14px" />
        </q-item-section>
      </q-item>
      <q-item :to="{path:'/customer/'+info.id+'/orders',query:{t:Date.now()}}">
        <q-item-section>
          <q-item-label>投注记录</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-icon name="arrow_forward_ios" size="14px" />
        </q-item-section>
      </q-item>
      <!-- DELAY 彩民支付管理 -->
      <!-- <q-item :to="'/customer/' + info.id+'/payment/setting'">
        <q-item-section>
          <q-item-label>支付管理</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-icon name="arrow_forward_ios" size="14px" />
        </q-item-section>
      </q-item> -->
    </q-list>
    <q-list separator class="bg-white q-mt-sm">
      <q-item>
        <q-item-section>
          <q-item-label>设为销售</q-item-label>
          <q-item-label caption>佣金{{ info.agent_brokerage }} %</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-toggle
            :model-value="info.agent"
            :false-value="0"
            :true-value="1"
            @update:model-value="toggleAgent"
          />
        </q-item-section>
      </q-item>
      <q-item clickable @click="openAgentDialog">
        <q-item-section>
          <q-item-label>所属销售</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-item-label
            >{{ info.agentor?.remark||info.agentor?.nickname || '' }}<q-icon name="arrow_forward_ios" size="14px"
          /></q-item-label>
        </q-item-section>
      </q-item>
      <q-item>
        <q-item-section>
          <q-item-label>他的来源</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-item-label>{{
            info.useragent?.match(/android|ios|ipod|ipad/i)?.[0]
          }}</q-item-label>
        </q-item-section>
      </q-item>
    </q-list>
    <q-list separator class="bg-white q-mt-sm q-mb-lg">
      <q-item>
        <q-item-section>
          <q-item-label>星标用户将在首页置顶</q-item-label>
          <q-item-label caption>设为星标用户</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-toggle
            :model-value="info.star"
            :false-value="0"
            :true-value="1"
            @update:model-value="toggleStar"
          />
        </q-item-section>
      </q-item>
    </q-list>
    <q-dialog
      v-model="agentDialogVisble"
      position="right"
      full-height
      square
      maximized
      class="dialog-full-height"
    >
      <q-card style="width: 85vw" class="column">
        <div class="safe-padding-top"></div>
        <div class="col overflow-y">
          <q-list class="bg-white">
            <template v-if="info.agentor">
            <q-item dense class="bg-grey-3 text-grey-7 items-end">
              所属销售
            </q-item>
            <q-item>
              <q-item-section avatar>
                <q-item-label class="row items-center">
                  <UserAvatar src="" size="md"
                /></q-item-label>
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ info.agentor.remark||info.agentor.nickname }}</q-item-label>
                <q-item-label caption>{{ info.agentor.created_at }}</q-item-label>
              </q-item-section>
            </q-item>
          </template>
            <q-item dense class="bg-grey-3 text-grey-7 items-end">
              转移至
            </q-item>
            <template v-for="item,i in agentorList" :key="i">
            <q-item v-if="item.id!=info.id && item.id!=info.agent_id">
              <q-item-section avatar>
                <q-item-label class="row items-center">
                  <q-radio v-model="agent_id" :val="item.id" size="sm" />
                  <UserAvatar :src="item.avatar_url||item.avatar" size="md"
                /></q-item-label>
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ item.nickname || item.name }}</q-item-label>
                <q-item-label caption>{{ item.created_at }}</q-item-label>
              </q-item-section>
            </q-item>
          </template>
          </q-list>
        </div>
        <q-btn unelevated="" color="primary" square :disable="!agent_id" @click="changeAgent">
        <div class="safe-padding-bottom">确定</div>
      </q-btn>
      </q-card>
    </q-dialog>
    <template #footer>
      <q-footer class="bg-white">
        <div class="row">
          <q-btn
            class="col q-py-sm"
            unelevated
            square
            color="white"
            text-color="dark"
            @click="resetPassword('resetPassword')"
          >
            <span class="safe-padding-bottom">一键重置
              <div class="text-caption">(<span class="text-red">登录</span>密码)</div>
            </span>
          </q-btn>
          <q-separator vertical />
          <q-btn
            class="col q-py-sm"
            unelevated
            square
            color="white"
            text-color="dark"
            @click="resetPassword('resetPayPassword')"
          >
            <span class="safe-padding-bottom">一键重置
              <div class="text-caption">(<span class="text-red">支付</span>密码)</div>
            </span>
          </q-btn>
          <q-btn
            :href="'tel:' + info.phone"
            class="col q-py-sm"
            unelevated
            square
            color="primary"
          >
          <span class="safe-padding-bottom">打电话</span>
        </q-btn>
      </div>
      </q-footer>
    </template>
    <q-dialog
      :model-value="!!moneyDialog"
      @update:model-value="moneyDialog = 0"
    >
      <q-card class="full-width">
        <q-card-section class="text-center q-pb-none">
          {{ moneyDialog == "incr" ? "加款" : (moneyDialog == 'recharge'?'充值':"扣款") }}
        </q-card-section>
        <q-card-section>
          <q-input
            dense
            v-model="dialogForm.money"
            type="number"
            placeholder="请输入金额"
            lazy-rules
            :rules="[Rules.required, Rules.greaterThan(0)]"
          />
          <q-input
            dense
            v-model="dialogForm.password_pay"
            lazy-rules
            :rules="[Rules.required, Rules.password]"
            type="password"
            placeholder="请输入支付密码"
          />
          <!-- <q-input
            v-model="dialogForm.password_pay_confirmation"
            dense
            lazy-rules
            :rules="[
              Rules.required,
              Rules.password,
              Rules.sameAs(
              dialogForm.password_pay,
              '确认支付密码与支付密码不一致'
            )
            ]"
            type="password"
            placeholder="确认支付密码"
          /> -->
          <q-input dense v-model="dialogForm.remark" placeholder="请输入备注" />
        </q-card-section>
        <q-separator size="0.5px" />
        <q-card-actions align="stretch" class="row">
          <q-btn
            color=""
            class="col"
            unelevated=""
            flat
            @click="moneyDialog = 0"
            >取消</q-btn
          >
          <q-btn
            color="primary"
            class="col"
            unelevated=""
            flat
            @click="changeBalance"
            >确认</q-btn
          >
        </q-card-actions>
      </q-card>
    </q-dialog>
  </PageLayout>
</template>
<script setup>
import { api } from "boot/axios";
import { Rules,formatMoney,formatDate } from "src/utils/tools";
import { ref, reactive, watch } from "vue";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import { useSelfStore } from 'stores/self';

import { safeCopyToClipboard } from "src/utils/tools.js"

const store = useSelfStore()
const $q = useQuasar();
const route = useRoute();

const seePhone = ref(false);
const info = ref({});
function toggleStar(star) {
  updateCustomerInfo({star})
}
// 开启、关闭代理
function toggleAgent(agent) {
  if (agent) {
    $q.dialog({
      title: "设置销售佣金",
      // message: '请输入备注',
      prompt: {
        model: info.value.agent_brokerage || 0,
        isValid: (val) => val * 1 >= 1 && val * 1 < 100, // << here is the magic
        type: "number", // optional
        placeholder: "请输入佣金"
      },
      cancel: true,
      ok: {}
    }).onOk((agent_brokerage) => {
      // console.log('>>>> OK, received', data)
      updateCustomerInfo({
          agent_brokerage,
          agent
        })
    });
    return;
  }
  updateCustomerInfo({ agent })
}
function editRemarkName() {
  $q.dialog({
    title: "设置备注",
    // message: '请输入备注',
    prompt: {
      model: "",
      isValid: (val) => val.length > 2, // << here is the magic
      type: "text", // optional
      placeholder: "请输入备注"
    },
    cancel: {
      label: "取消",
      flat:true
    },
    ok: "确定"
  }).onOk((data) => {
    // console.log('>>>> OK, received', data)
    updateCustomerInfo({remark: data })
  });
}
function load() {
  api
    .getCustomerInfo({ customer_id: route.params.id })
    .then((res) => {
      info.value = res;
    })
    .catch((e) => {
      $q.notify({ type: "negative", message: e.message });
    })
    .finally(() => {
      $q.loading.hide();
    });
}
$q.loading.show();
load();

// 价款扣款
const moneyDialog = ref(0);
const dialogForm = reactive({
  customer_id: route.params.id,
  money: "",
  password_pay: "",
  // password_pay_confirmation: "",
  remark: ""
});

function changeBalance() {
  $q.loading.show()
  api
    .changeBalance(moneyDialog.value, dialogForm)
    .then((res) => {
      load();
      $q.notify({ type: "positive", message: (moneyDialog.value == 'incr'?'加款':(moneyDialog.value=='recharge'?"充值":"扣款"))+'成功' });
      moneyDialog.value = 0
    })
    .catch((e) => {
      $q.notify({ type: "negative", message: e.message });
    }).finally(()=>{
      $q.loading.hide()
    });
}

function resetPassword(funcName) {
  const str = funcName === 'resetPassword'?'登录':'支付'
  $q.dialog({
    title: "系统提示",
    message: `确定重置用户<span class="text-red">${str}</span>密码？`,
    html: true,
    cancel: true,
    persistent: true
  })
    .onOk(() => {
      $q.loading.show()
      api[funcName]({ customer_id: route.params.id })
        .then((e) => {
          $q.notify({
            type: "positive",
            message: `重置${str}密码成功，新密码为${e}`,
            timeout: 0,
            actions: [
              { label: '关闭', color: 'white'},
              {
                label: '复制密码',
                color: 'white',
                textColor: "black",
                flat: false,
                unelevated: true,
                handler: () => {
                  safeCopyToClipboard(e)
                }
              }
            ]
          });
        })
        .catch((e) => {
          $q.notify({ type: "negative", message: e.message });
        }).finally(()=>{
          $q.loading.hide()
        });
    })
    .onCancel(() => {
      // console.log('>>>> Cancel')
      // }).onDismiss(() => {
      // console.log('I am triggered on both OK and Cancel')
    });
}

function updateCustomerInfo(data){
  $q.loading.show()
  return api
    .updateCustomerInfo({ customer_id: info.value.id, ...data })
    .then((res) => {
      for(let p in data){
        info.value[p] = data[p]
      }
    })
    .catch((e) => {
      $q.notify({ type: "negative", message: e.message });
      return Promise.reject(e)
    }).finally(()=>{
      $q.loading.hide()
    });
}
// 设置代理
const agentDialogVisble = ref(false);
const agent_id = ref("");
const agentorList = ref([])
function openAgentDialog(){
  agentDialogVisble.value = true
  if(!agentorList.value.length){
    api.getCustomerList({agent:1}).then(res=>{
      agentorList.value = res.data
    })
  }
}
function changeAgent(){
  let agent = agentorList.value.find(item=>item.id == agent_id.value)
  $q.dialog({
    message: '确定将用户转到该销售'+(agent?.nickname||agent?.name||'')+'名下吗？',
    cancel: true
  }).onOk(()=>{
    updateCustomerInfo({agent_id:agent_id.value}).then(()=>{
      agentDialogVisble.value = false
      agent_id.value = ''
      load()
    })
  })
}
</script>
