
<template>
  <a-drawer
    v-model:visible="vdata.isShow" 
    :title=" vdata.isAdd ? '新增终端' : '修改终端' "
    width="60%"
    :mask-closable="false"
    @close="vdata.isShow = false"
  >
    <a-form ref="infoFormModel" :model="vdata.saveObject" :label-col="{span: 6}" :wrapper-col="{span: 15}" :rules="rules">
      <a-row justify="space-between" type="flex">
        <a-col :span="12">
          <a-form-item label="选择门店" name="storeId">
            <a-select v-model:value="vdata.saveObject.storeId" style="width:300px;" :disabled="!vdata.isAdd">
              <a-select-option key="">选择门店</a-select-option>
              <a-select-option v-for="(item) in vdata.mchStoreList" :key="item.storeId">{{ item.storeName }} [{{ item.storeId }}]</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col v-if="$access('ENT_MCH_APP_LIST')" :span="12">
          <a-form-item label="选择应用" name="appId">
            <a-select v-model:value="vdata.saveObject.appId" style="width:300px;">
              <a-select-option key="">选择应用</a-select-option>
              <a-select-option v-for="(item) in vdata.mchAppList" :key="item.appId">{{ item.appName }} [{{ item.appId }}]</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row justify="space-between" type="flex">
        <a-col :span="12">
          <!-- 需要先选择商户 -->
          <a-form-item label="设备类型" name="trmType">
            <a-radio-group v-model:value="vdata.saveObject.trmType" :disabled="!vdata.isAdd || !vdata.saveObject.storeId" @change="changeTypeFunc">
              <a-radio :value="1">终端</a-radio>
              <a-radio :value="2">扫码POS</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="state">
            <a-radio-group v-model:value="vdata.saveObject.state">
              <a-radio :value="1">启用</a-radio>
              <a-radio :value="0">禁用</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row justify="space-between" type="flex">
        <a-col :span="12">
          <a-form-item label="设备编号" name="trmNo">
            <a-input v-model:value="vdata.saveObject.trmNo" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="设备名称" name="trmName">
            <a-input v-model:value="vdata.saveObject.trmName" />
          </a-form-item>
        </a-col>
      </a-row>


      <a-divider />

      <!-- 引入地图组件  -->
      <JeepayAmap ref="jeepayAmapRef" />

      <!-- 选择pos列表  -->
      <SelectPosList ref="selectPosListRef" @selectFinishFunc="selectPosFinishFunc" />
    </a-form>
  
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="vdata.isShow = false"><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_MCH_TERMINAL, API_URL_MCH_STORE_LIST, API_URL_MCH_APP }from '@/api/manage'
import { reactive, ref, nextTick, getCurrentInstance } from 'vue'
import SelectPosList from './SelectPosList.vue'
import ruleGenerator from '@/utils/ruleGenerator'

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

const infoFormModel = ref()
const selectPosListRef = ref()
const jeepayAmapRef = ref()

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

const vdata : any = reactive({

  confirmLoading: false, // 显示确定按钮loading图标
  isAdd: true, // 新增 or 修改页面标识
  isShow: false, // 是否显示弹层/抽屉
  saveObject: {} as any, // 数据对象
  recordId: null, // 更新对象ID

  mchAppList: [],
  mchStoreList: []

})

const rules = {
  trmNo: [ruleGenerator.requiredInput('设备编号') ],
  trmName: [ruleGenerator.requiredInput('设备名称') ],
  trmType: [ruleGenerator.requiredSelect('设备类型', 'number') ],
  storeId: [ruleGenerator.requiredSelect('门店', 'number') ],
  state: [ruleGenerator.requiredSelect('状态', 'number') ],
  // areacode: [ruleGenerator.requiredSelect('位置编码', 'array') ],
  // address: [ruleGenerator.requiredInput('布放位置') ],
  // lnglat: [ruleGenerator.requiredInput('经纬度') ],
}


function selectPosFinishFunc(val, row){

  if(!val){
    return $infoBox.message.error('选择信息不完整！')
  }

  vdata.saveObject.trmNo = row.deviceNo
  vdata.saveObject.trmName = row.deviceName

  selectPosListRef.value.close()

}


function handleOkFunc(){

  let mapData = jeepayAmapRef.value.getMapData()
   if(!mapData || mapData.areacode.length == 0 || mapData.areacodeNames.length == 0 || !mapData.address || !mapData.lnglat){
     return $infoBox.message.error('请选择地理位置')
   }

   if(mapData.lnglat.indexOf(',') < 0){
     return $infoBox.message.error('请输入正确的经纬度')
   }

  infoFormModel.value.validate().then(valid =>{

    vdata.confirmLoading = true // 打开按钮上的 loading
    
    vdata.saveObject.lng = mapData.lnglat.split(',')[0]
    vdata.saveObject.lat = mapData.lnglat.split(',')[1]
    vdata.saveObject.detailAddress = mapData.address
    vdata.saveObject.areacode = JSON.stringify(mapData.areacode)
    vdata.saveObject.areacodeNames = JSON.stringify(mapData.areacodeNames)

    if(vdata.isAdd){

        req.add(API_URL_MCH_TERMINAL, vdata.saveObject).then(res => {

        $infoBox.message.success('新增成功')
        vdata.isShow = false 
        props.callbackFunc() // 刷新列表
      }).finally(() => vdata.confirmLoading = false)

    }else{
      req.updateById(API_URL_MCH_TERMINAL, vdata.recordId, vdata.saveObject).then(res => {
          $infoBox.message.success('更新成功')
          vdata.isShow = false 
          props.callbackFunc() // 刷新列表

      }).finally(() => vdata.confirmLoading = false)
    }
   
  })
}

// 更改设备类型func 
function changeTypeFunc(e){
  // pos 
  if(e.target.value == 2){
    selectPosListRef.value.show({deviceType: 3, mchNo: vdata.saveObject.mchNo, appId: vdata.saveObject.appId, storeId: vdata.saveObject.storeId})
  }
}

// 显示 & 初始化地图
function show (recordId) { // 弹层打开事件

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


// 请求接口，获取商户所有门店，只有次数进行pageSize=-1传参
  req.list(API_URL_MCH_STORE_LIST, { pageSize: -1 }).then(res => {
    vdata.mchStoreList = res.records
  })

  // 请求接口，获取商户所有应用，只有次数进行pageSize=-1传参
  if($access('ENT_MCH_APP_LIST')){
    req.list(API_URL_MCH_APP, { pageSize: -1 }).then(res => {
      vdata.mchAppList = res.records
    })
  }


  vdata.isAdd = !recordId
  vdata.recordId = recordId
  // 数据恢复为默认数据
  vdata.saveObject = {}
  vdata.confirmLoading = false // 关闭loading

  let initMapData : any = {}


  if(recordId){

      req.getById(API_URL_MCH_TERMINAL, recordId).then(res => {
        if(res){
          vdata.saveObject = res
          initMapData.areacode = JSON.parse(res.areacode)
          initMapData.areacodeNames = JSON.parse(res.areacodeNames)
          initMapData.lnglat = res.lng + ',' + res.lat
          initMapData.address = res.detailAddress
        }
        vdata.isShow = true // 立马展示弹层信息
        nextTick(() => jeepayAmapRef.value.init(initMapData))
      })

  }else{

    vdata.isShow = true // 立马展示弹层信息
    nextTick(() => jeepayAmapRef.value.init(initMapData))
  }

}

defineExpose({show})
</script>
