<template>
  <a-drawer
    v-model:visible="vdata.visible"
    title="门店绑定"
    placement="right"
    :closable="true"
    width="80%"
    @ok="handleOkFunc"
    @close="onClose"
  >
    <div class="modal-div">
      <!-- 门店列表 -->
      <div class="modal-div1">
        <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="resetFunc">
          <jeepay-text-up v-model:value="vdata.searchData['storeId']" :placeholder="'门店ID'" />
          <jeepay-text-up v-model:value="vdata.searchData['storeName']" :placeholder="'门店名称'" />
        </JeepaySearchForm>

        <div class="list-table">
          <JeepayTable
            ref="infoTable"
            :initData="false"
            :reqTableDataFunc="reqTableDataFunc"
            :tableColumns="tableColumns"
            :searchData="vdata.searchData"
            rowKey="storeId"
            scrollX="100%"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'storeId'">
                {{ record.storeId }}
              </template>

              <template v-if="column.key === 'storeName'">
                {{ record.storeName }}
              </template>

              <template v-if="column.key === 'bindState'">
                <JeepayTableColState :badgeTextArray="['未绑店长', '已绑店长', '未知']" :state="vdata.selectRecordIdList.includes(record.storeId) ? 1 : 0" :showSwitchType="!record.hasDirector? true: false" :onChange="(state) => { return updateBindState(record.storeId, state)}" />
              </template>
            </template>
          </JeepayTable>
        </div>
      </div>
    </div>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="onClose">
        <close-outlined />取消
      </a-button>
      <a-button type="primary" :loading="vdata.confirmLoading" @click="handleOkFunc">
        <check-outlined />保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { req, API_URL_SYS_USER_LIST, API_URL_MCH_STORE_LIST, reqLoad } from '@/api/manage'
import { message } from 'ant-design-vue'
import { reactive, ref, nextTick } from 'vue'

const infoFormModel = ref()
const props = defineProps({
  callbackFunc: {
    type: Function,
    default: () => ({})
  }
})

function resetFunc(){ 
  vdata.searchData = {} 
  vdata.cycleType = 'date'
}

const vdata :any = reactive({
  visible: false,
  loading: false, // 按钮上的loading
  value: 1, // 单选框默认的值
  confirmLoading: false, // 显示确定按钮loading图标
  isAdd: true, // 新增 or 修改页面标识
  saveObject: {} as any, // 数据对象
  recordId: null, // 更新对象ID
  userType: null, // 用户类型
  searchData: {},
  selectRecordIdList: [],
  belongInfoId: ''
})

const tableColumns = ref([
  { key: 'storeId', title: '门店ID'},
  { key: 'storeName', title: '门店名称'},
  { key: 'bindState', title: '绑定状态'},
])
// 当前 table 组件
const infoTable = ref()

defineExpose({ show })

function show(recordId, userType, belongInfoId) { // 弹层打开事件
  vdata.visible = true
  vdata.recordId = recordId
  vdata.userType = userType
  vdata.belongInfoId = belongInfoId
  vdata.selectRecordIdList = []

  if (infoFormModel.value !== undefined) {
    infoFormModel.value.resetFields()
  }

  vdata.confirmLoading = false // 关闭loading
  req.getById(API_URL_SYS_USER_LIST, recordId).then(res => {
    vdata.saveObject = res

    if(vdata.saveObject.storeIdList) {
      vdata.selectRecordIdList = vdata.saveObject.storeIdList
    }

  })
  nextTick(() => infoTable.value.refTable(true))
}

function handleOkFunc() { // 点击【确认】按钮事件
  vdata.loading = true // 打开按钮上的 loading
  vdata.confirmLoading = true // 显示loading

  reqLoad.add(API_URL_SYS_USER_LIST + `/bindStore/` + vdata.recordId, {storeIdList: vdata.selectRecordIdList.join(',')}).then(res => {
    message.success('绑定成功')
    vdata.visible = false
    vdata.loading = false
    props.callbackFunc() // 刷新列表
  }).catch((res) => {
    vdata.confirmLoading = false
  })
}
// 点击遮罩层关闭抽屉
function onClose() {
  vdata.visible = false
}

// 请求table接口数据
function reqTableDataFunc (params){
  return req.list(API_URL_MCH_STORE_LIST + `/bindStoreList`, Object.assign({ userId: vdata.recordId, userType :vdata.userType, mchNo: vdata.belongInfoId }, params))
}

// 表格搜索
function searchFunc () {
  nextTick(() => {
    infoTable.value.refTable(true)
  })
}

// 表格行开关开启、关闭
function updateBindState(recordId, bindState) {
  return new Promise<void>((resolve, reject) => {
     nextTick(() => {
      if (bindState) {
        if(vdata.userType == '12') {
          vdata.selectRecordIdList = []
        }
        vdata.selectRecordIdList.push(recordId)
      } else {
        vdata.selectRecordIdList.splice(vdata.selectRecordIdList.indexOf(recordId), 1)
      }
      resolve()
    })
  })
}

</script>
