<style scoped lang="scss">
.system-container {

  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    overflow: auto;

    .el-table {
      flex: 1;
    }

  }
}

.page-content {
  margin-bottom: 20px;
}

.page-pager {
  background-color: #fff;
  height: 24px;
}
</style>
<template>
  <div class="system-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">


      <el-form
          :model="state.formQuery"
          ref="queryRef"
          size="default" label-width="0px" class="mt5 mb5">
        <el-input
            v-model="state.formQuery.name"
            placeholder="优惠券名称"
            clearable
            @blur="loadData(true)"
            class="wd150 mr10">
        </el-input>
        <!--        <ext-date-picker
                    v-model="state.formQuery.startTime"
                    placeholder="开始时间"
                    clearable
                    @blur="loadData(true)"
                    class="wd150 mr10">
                </ext-date-picker>
                <ext-date-picker
                    v-model="state.formQuery.endTime"
                    placeholder="结束时间"
                    clearable
                    @blur="loadData(true)"
                    class="wd150 mr10">
                </ext-date-picker>-->
        <ext-d-select
            v-model="state.formQuery.couponType"
            placeholder="券种"
            type="Activity.couponType"
            clearable
            @blur="loadData(true)"
            class="wd150 mr10">
        </ext-d-select>


        <el-button class="ml10" plain size="default" type="success" @click="loadData(true)">
          <SvgIcon name="ele-Search"/>
          查询
        </el-button>
      </el-form>

      <el-table
          border
          stripe="stripe"
          :height="state.tableData.height"
          highlight-current-row
          current-row-key="id"
          row-key="id"
          :data="state.tableData.data"
          v-loading="state.tableData.loading"
          @row-dblclick="onRowClick('view',$event)"
          @selection-change="handleTableSelectionChange"
          @sort-change="handleTableSortChange">
        <template #empty>
          <el-empty></el-empty>
        </template>
        <el-table-column
            v-for="field in state.tableData.columns"
            :key="field.prop"
            :label="field.label"
            :column-key="field.prop"
            :width="field.width"
            :min-width="field.minWidth"
            :fixed="field.fixed"
            :sortable="field.sortable"
            :show-overflow-tooltip="!field.fixed&&field.width>150"
        >
          <template #default="{row}">
            <template v-if="field.prop==='expand'">
              <p style="padding-left: 2em;" v-html="row[field.prop]"></p>
            </template>
            <template v-else-if="field.prop==='period'">
              {{ row.startTime }} ~ {{ row.endTime }}
            </template>
            <template v-else-if="field.prop==='couponType'">
              <ext-d-label type="Activity.couponType" v-model="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="field.prop==='status'">
              <ext-d-label type="Coupon.status" v-model="row[field.prop]"></ext-d-label>
            </template>
            <template v-else-if="field.prop==='minServiceMoney'">
              {{ u.fmt.fmtMoney(row.minServiceMoney) }}
            </template>
            <template v-else-if="field.prop==='allowStacke'">
              {{ row.allowStacke ? '是' : '否' }}
            </template>
            <template v-else-if="field.prop==='action'">
              <!--              <el-button v-auth="'coupon.list'" size="small" plain type="success" @click="onRowClick('view',row)">查看</el-button>-->
              <el-button v-show="row.receiveType==='Release'" v-auth="'coupon.modify'" size="small" plain type="danger" @click="onCouponDispatch(row)">发券</el-button>
            </template>
            <template v-else>
              <div>{{ row[field.prop] }}</div>
            </template>

          </template>
        </el-table-column>
      </el-table>

      <ext-page class="page-pager" v-model:value="state.pageQuery" @change="loadData(false)"/>
    </el-card>
  </div>
  <ActivityDialog ref="activityDialogRef" @refresh="loadData(true)"/>
  <ExtSContainer ref="userSelectDialogRef"></ExtSContainer>
  <AccountMobileUpload ref="accountMobileUploadDialogRef" @on-import-finish="handleImportAccountPhone"></AccountMobileUpload>
</template>

<script setup lang="ts" name="ActivityList">
import {defineAsyncComponent, reactive, onMounted, onBeforeMount, ref, getCurrentInstance, nextTick, onBeforeUnmount} from 'vue';
import {$body, $get} from "/@/utils/request";
import {Msg} from "/@/utils/message";


import ExtPage from '/@/components/form/ExtPage.vue'

import ExtDSelect from "/@/components/form/ExtDSelect.vue";
import ExtDatePicker from "/@/components/form/ExtDatePicker.vue";
import ExtDLabel from "/@/components/form/ExtDLabel.vue";
import u from "/@/utils/u";

const ActivityDialog = defineAsyncComponent(() => import("/@/views/admin/activity/coupon/dialog.vue"));
const ExtSContainer = defineAsyncComponent(() => import('/@/components/form/ExtSContainer.vue'));
const AccountMobileUpload = defineAsyncComponent(() => import('./upload.vue'));

//定义引用
const queryRef = ref();
const activityDialogRef = ref();
const userSelectDialogRef = ref();
const accountMobileUploadDialogRef = ref();

//定义变量
const state = reactive({
  formQuery: {
    discountType: 'Coupon'
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      {
        label: '优惠券名称', prop: 'name', resizable: true, width: 170, fixed: 'left'
      },
      {label: '状态', prop: 'status', resizable: true, width: 80},
      {label: '券种', prop: 'couponType', resizable: true, width: 80},
      {label: '活动时间', prop: 'period', resizable: true, width: 350},
      {label: '优惠券描述', prop: 'couponDesc', align: 'center', width: 200},
      {label: '服务费门槛（元）', prop: 'minServiceMoney', resizable: true, width: 180},
      {label: '折扣率%', prop: 'discount', resizable: true, width: 130},
      {label: '已领取/发放数量', prop: 'claimedQuantity', resizable: true, width: 140},
      // {label: '优惠允许叠加', prop: 'allowStacke', resizable: true, width: 130},
      // {label: '数量限制', prop: 'quantity', resizable: true, width: 130},
      {label: '创建时间', prop: 'createTime', resizable: true, width: 180},
      {label: '更新时间', prop: 'updateTime', resizable: true, width: 180},
      {
        label: '操作', prop: 'action', width: 100, align: 'center', fixed: 'right',
      }
    ],
  },
  handleCoupon: null
})


// 监听双向绑定 modelValue 的变化
// watch(
//         () => state.pageIndex,
//         () => {
//
//         }
// );

//生命周期钩子
onBeforeMount(() => {
})

onMounted(() => {
  loadData();

  nextTick(() => {
    let bodyHeight = document.body.clientHeight;
    let queryHeight = queryRef.value.$el.clientHeight;
    state.tableData.height = bodyHeight - queryHeight - 320
  })

});

onBeforeUnmount(() => {
})


//region 方法区
// 初始化表格数据
const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  $get(`/coupon/list`, {...state.formQuery, ...state.pageQuery}).then((res: any) => {
    let {list, total} = res;
    state.tableData.data = list;
    state.pageQuery.total = total;
    state.tableData.loading = false;
  }).catch(e => {
    console.error(e)
    state.tableData.loading = false;
  })
};

const handleRowClick = (event) => {
  console.log(event)
  activityDialogRef.value.open("view", event);
};

const onRowClick = (type: string, row: any) => {
  activityDialogRef.value.open(type, row);
};

const onCouponDispatch = (row: any) => {
  state.handleCoupon = row;
  Msg.confirm(`请选择发券方式`, '操作', {'ok': '选择用户发放', 'cancel': '导入号码发放'}, '').then(() => {
    //选择用户
    let config = {
      columns: [
        {label: '手机号', query: true, width: 120, prop: 'mobilePhone', resizable: true, type: 'text'},
        // {label: '余额',query: false, width: 80, prop: 'balance', resizable: true,type:'number'},
        {label: '状态', query: true, width: 80, prop: 'status', align: 'center', type: 'dict', conf: {dict: 'User.status'}},
      ],
      query: {},
      url: 'custom/listUser',
      method: 'get'
    }
    userSelectDialogRef.value.open(handleChooseAccount, true, config, []);
  }).catch(e => {
    console.log(e)
    if ('close' == e) return;
    //上传用户手机号
    accountMobileUploadDialogRef.value?.open();
  });
};

const handleChooseAccount = (accountList: Array<any>) => {
  console.log(accountList)
  if (u.isEmptyOrNull(accountList)) {
    Msg.message('请选择用户', 'error')
    return;
  }

  Msg.prompt(`请输入发放数量`, '操作', {pattern: /^[0-9]*$/, error: '只能输入不小于1的数字'}).then((detail) => {
    let count = detail.value;
    if (detail.action != 'confirm' || !count || count < 1) return;
    let params = {
      userIds: accountList.map(k => k.userId),
      couponId: state.handleCoupon.id,
      couponCount: count
    }
    Msg.showLoading(`发放中`)
    $body(`coupon/issueCoupons`, params).then(() => {
      Msg.message('发放成功')
    }).catch(e => {
      Msg.message('发放失败', 'error')
    })
  })

}

const handleImportAccountPhone = (phoneList: Array<any>) => {
  console.log(phoneList)
  if (u.isEmptyOrNull(phoneList) || u.isEmptyOrNull(phoneList.dataList)) {
    Msg.message('请导入用户手机号', 'error')
    return;
  }
  Msg.prompt(`请输入发放数量`, '操作', {pattern: /^[0-9]*$/, error: '只能输入不小于1的数字'}).then((detail:any) => {
    let count = detail.value;
    if (detail.action != 'confirm' || !count || count < 1) return;
    let params = {
      phones: phoneList?.dataList?.map(k => k.mobilePhone),
      couponId: state.handleCoupon.id,
      couponCount: count
    }
    Msg.showLoading(`发放中`)
    $body(`coupon/issueCoupons`, params).then(() => {
      Msg.message('发放成功')
    }).catch(e => {
      Msg.message('发放失败', 'error')
    })
  })

}

const handleTableSelectionChange = (selection: any) => {
  console.log("handleTableSelectionChange>>", selection)
  // emit("on-check-change", selection)
}

const handleTableSortChange = (column, prop, order) => {
  console.log("handleTableSortChange>>", column, prop, order)
  // emit("on-sort-change", column)
}


//endregion


// 暴露变量
// defineExpose({
//     loadData,
// });
</script>
