<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.stationId ? $t('table.create') : $t('table.edit')"
    :close-on-click-modal="false"
    width="760px"
    class="page-station-add-or-update"
    @closed="onClosed"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      style="min-width:630px;"
    >
      <el-form-item
        v-if="!dataForm.stationId"
        prop="stockMode"
        label="库存模式"
      >
        <el-radio-group
          v-model="dataForm.stockMode"
        >
          <el-radio :label="1">
            共享总部库存
            <el-tooltip
              class="box-item"
              effect="dark"
              content="门店产生销售时，扣减默认仓库的商品库存"
              placement="top"
            >
              <el-icon style="vertical-align: middle">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </el-radio>
          <el-radio :label="2">
            独立销售库存
            <el-tooltip
              class="box-item"
              effect="dark"
              content="门店产生销售时，扣减默认该门店的商品库存"
              placement="top"
            >
              <el-icon style="vertical-align: middle">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        class="stationName"
        :label="$t('delivery.station.stationNames')"
        prop="stationName"
        style="width:624px;"
      >
        <el-input
          v-model="dataForm.stationName"
          maxlength="50"
          show-word-limit
          @change="onCheckStationNames"
        />
      </el-form-item>
      <el-form-item
        label="门店图片"
        prop="imgUrl"
      >
        <div>
          <img-upload v-model="dataForm.imgUrl" />
          <el-button
            v-if="dataForm.imgUrl"
            @click="dataForm.imgUrl = ''"
          >
            删除
          </el-button>
        </div>
      </el-form-item>
      <el-form-item
        :label="$t('admin.phoNumber')"
        prop="mobile"
      >
        <el-col :span="4">
          <el-input
            v-model="dataForm.mobilePrefix"
            :placeholder="$t('admin.areaCode')"
            maxlength="10"
            @change="onCheckPhonePrefix"
          />
        </el-col>
        <el-col :span="0.5">
          <span>—</span>
        </el-col>
        <el-col :span="9">
          <el-input
            v-model="dataForm.mobile"
            :placeholder="$t('admin.number')"
            maxlength="11"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        :label="$t('admin.businTime')"
        prop="shopTime"
      >
        <el-time-picker
          v-model="timeDateModeVO.shopTime[0]"
          :clearable="false"
          format="HH:mm"
          :placeholder="$t('admin.businStartTime')"
          @change="onStartChange"
        />
        <span style="margin: 0 10px;">{{ $t('admin.timeTip') }}</span>
        <el-time-picker
          v-model="timeDateModeVO.shopTime[1]"
          :clearable="false"
          format="HH:mm"
          :placeholder="$t('admin.businEndTime')"
          @change="onEndChange"
        />
      </el-form-item>
      <el-form-item :label="$t('delivery.station.businessStatus')">
        <el-radio-group
          v-model="status"
          :disabled="dataForm.status > 1"
        >
          <el-radio :label="1">
            {{ $t('delivery.station.business') }}
          </el-radio>
          <el-radio :label="0">
            {{ $t('delivery.station.close') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="$t('delivery.station.shopAddr')"
        prop="areaInfo"
      >
        <div class="area-select">
          <el-form-item prop="province">
            <el-select
              v-model="dataForm.provinceId"
              :placeholder="$t('tip.select')"
              @change="onSelectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('address.city')"
            label-width="50px"
            prop="city"
          >
            <el-select
              v-model="dataForm.cityId"
              :placeholder="$t('address.city')"
              @change="onSelectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('address.area')"
            label-width="50px"
            prop="area"
          >
            <el-select
              v-model="dataForm.areaId"
              :placeholder="$t('address.area')"
              @change="onSelectArea(true)"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form-item>

      <el-form-item
        class="addr"
        :label="$t('delivery.station.shopDetailAddr')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          maxlength="100"
          show-word-limit
          @change="onMapLocation(true)"
        />
      </el-form-item>
      <el-form-item>
        <div class="map">
          <tmap
            ref="tmapRef"
            :lat-lng="latLng"
            @change-lat-lng="onChangeLatLng"
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button
          @click="visible = false"
        >{{ $t('table.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="onSubmit()"
        >{{ $t('table.submit') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import * as api from '@/api/delivery/station'
import * as addrApi from '@/api/system/addr-manage'
import { ElMessage } from 'element-plus'

const emit = defineEmits([
  'close',
  'refreshDataList'
])

const dataForm = reactive({
  stationId: null,
  stationName: null,
  imgUrl: null,
  mobilePrefix: null,
  mobile: null,
  startTime: '',
  endTime: '',
  status: 1,
  provinceId: null,
  province: null,
  cityId: null,
  city: null,
  areaId: null,
  area: null,
  addr: null,
  lng: null,
  lat: null,
  timeDateModeVO: {},
  stockMode: 1
})
const timeDateModeVO = reactive({
  shopTime: [new Date(2020, 1, 1, 8, 0, 0), new Date(2020, 1, 1, 20, 0, 0)]
})

// 地址信息列表
const provinceList = reactive([])
const cityList = reactive([])
const areaList = reactive([])

const validateProvince = (rule, value, callback) => {
  if (!dataForm.province) {
    callback(new Error($t('admin.seleProv')))
  } else if (!dataForm.city) {
    callback(new Error($t('admin.seleCity')))
  } else if (!dataForm.area) {
    callback(new Error($t('admin.seleDC')))
  } else {
    callback()
  }
}
const validateShopTime = (rule, value, callback) => {
  if (!timeDateModeVO.shopTime) {
    callback(new Error($t('admin.seleBusTime')))
  } else {
    callback()
  }
}
const validateStationName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('admin.stationNameNoNull')))
  } else {
    callback()
  }
}
const validateAddr = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('admin.addrNoNull')))
  } else {
    callback()
  }
}

const validateMobile = (rule, value, callback) => {
  if (isMobile(value) || (dataForm.stationId && isStarMobile(value))) {
    callback()
  } else {
    callback(new Error('请输入正确的手机号'))
  }
}
const dataRule = {
  stationName: [
    { required: true, message: $t('admin.stationNameNoNull'), trigger: 'blur' },
    { validator: validateStationName, trigger: 'blur' }
  ],
  areaInfo: [
    { required: true, validator: validateProvince, trigger: 'blur' }
  ],
  shopTime: [
    { validator: validateShopTime, trigger: 'blur' }
  ],
  addr: [
    { required: true, message: $t('admin.addrNoNull'), trigger: 'blur' },
    { validator: validateAddr, trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: $t('admin.numberNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ]
}

const onClosed = () => {
  emit('close')
}
const onStartChange = (val) => {
  if (!val) {
    timeDateModeVO.shopTime[0] = new Date(2020, 1, 1, 8, 0, 0)
  }
}
const onEndChange = (val) => {
  if (!val) {
    timeDateModeVO.shopTime[1] = new Date(2020, 1, 1, 20, 0, 0)
  }
}

const dataFormRef = ref()
const isSubmit = ref(false)
const show = ref(false)
const status = ref(1)
const visible = ref(false)
const init = (stationId) => {
  dataForm.stationId = stationId || 0
  visible.value = true
  show.value = false
  isSubmit.value = false
  nextTick(() => {
    status.value = 1
    dataFormRef.value?.resetFields()
    cityList.length = 0
    areaList.length = 0
    dataForm.provinceId = null
    dataForm.cityId = null
    dataForm.areaId = null
    dataForm.phonePrefix = null
    timeDateModeVO.shopTime = [new Date(2020, 1, 1, 8, 0, 0), new Date(2020, 1, 1, 20, 0, 0)]
    onListAreaByParentId().then((data) => {
      onHandleArr(provinceList, data)
      if (dataForm.stationId) {
        onGetDataInfo()
      }
    })
  })
}

// 获取店铺详情数据
const onGetDataInfo = () => {
  api.getStationInfo(
    dataForm.stationId
  ).then((data) => {
    onHandleDataForm(data)
    status.value = dataForm.status === 1 ? 1 : 0
    timeDateModeVO.shopTime = JSON.parse(data.timeInfo).shopTime
    onListAreaByParentId(data.provinceId).then((data) => {
      onHandleArr(cityList, data)
    })
    onListAreaByParentId(data.cityId).then((data) => {
      onHandleArr(areaList, data)
    })
    if (data.lat && data.lng) {
      latLng.value = {
        lng: data.lng,
        lat: data.lat
      }
    }
  })
}

const onListAreaByParentId = (pid) => {
  let paramData
  if (!pid) {
    paramData = { level: 1 }
  } else {
    paramData = { parentId: pid }
  }
  return addrApi.page(paramData)
}

const onGetCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}

// 选择省
const onSelectProvince = (val) => {
  dataForm.cityId = null
  dataForm.city = ''
  areaList.length = 0
  dataForm.areaId = null
  dataForm.area = ''
  // 获取城市的select
  const { curNode, areas } = onGetCurrentChild(provinceList, val)
  if (areas) {
    onHandleArr(cityList, areas)
  } else {
    onListAreaByParentId(val).then((data) => {
      curNode.areas = data
      onHandleArr(cityList, data)
    })
  }
  onGetProvinceName() // 获取省名称
  onMapLocation(true)
}

// 选择市
const onSelectCity = (val) => {
  dataForm.areaId = null
  dataForm.area = ''
  // 获取区的select
  const { curNode, areas } = onGetCurrentChild(cityList, val)
  if (areas) {
    onHandleArr(areaList, areas)
  } else {
    onListAreaByParentId(val).then((data) => {
      curNode.areas = data
      onHandleArr(areaList, data)
    })
  }
  onGetCityName() // 获取市名称
  onMapLocation(true)
}

const onSelectArea = () => {
  onGetDistrictName() // 获取区名称
  onMapLocation(true)
}

const onCheckStationNames = () => {
  dataForm.stationName = dataForm.stationName.trim()
}

const onCheckPhonePrefix = () => {
  if (dataForm.mobilePrefix) {
    const reg = /^[0-9]*$/
    if (!reg.test(dataForm.mobilePrefix)) {
      onShowErrorMessage($t('admin.onlyInNum'))
      dataForm.mobilePrefix = null
      return false
    }
  }
}

// 判断时分秒大小
const onCompareTime = (starTimestamp, endTimestamp) => {
  const starTime = new Date(starTimestamp)
  const starHours = starTime.getHours()
  const starMinute = starTime.getMinutes()
  const starSecond = starTime.getSeconds()
  const endTime = new Date(endTimestamp)
  const endHours = endTime.getHours()
  const endMinute = endTime.getMinutes()
  const endSecond = endTime.getSeconds()
  if (starHours > endHours) {
    return true
  } else if (starHours === endHours) {
    if (starMinute > endMinute) {
      return true
    } else if (starMinute === endMinute) {
      if (starSecond > endSecond) {
        return true
      } else return starSecond === endSecond
    } else {
      return false
    }
  } else {
    return false
  }
}

// 表单提交
const isEditAddr = ref(false)
const onSubmit = () => {
  if (isEditAddr.value) {
    ElMessage.info($t('admin.mapPosi'))
    return
  }
  onGetAreaName()
  dataForm.lng = latLng.value.lng
  dataForm.lat = latLng.value.lat
  const timeDateMode = timeDateModeVO
  if (timeDateMode.shopTime) {
    if (timeDateMode.shopTime[0] instanceof Date) {
      timeDateMode.shopTime[0] = timeDateMode.shopTime[0].getTime()
    }
    if (timeDateMode.shopTime[1] instanceof Date) {
      timeDateMode.shopTime[1] = timeDateMode.shopTime[1].getTime()
    }
    if (onCompareTime(timeDateMode.shopTime[0], timeDateMode.shopTime[1])) {
      ElMessage.error($t('admin.busiTimeErr'))
      return
    }
    dataForm.timeInfo = JSON.stringify(timeDateMode)
  }
  if (!dataForm.areaId) {
    ElMessage.error('请选择所在地区')
    return
  }
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit.value) {
        return false
      }
      isSubmit.value = true
      dataForm.status = dataForm.status > 1 ? dataForm.status : status.value
      // 新增or更新
      onGetSaveOrUpdateReq(dataForm)
        .then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible.value = false
              emit('refreshDataList')
            }
          })
        }).catch(() => {
          isSubmit.value = false
        })
    }
  })
}

// 获取新增or更新请求
const onGetSaveOrUpdateReq = (dataForm) => {
  if (dataForm.stationId) {
    return api.updateStation(dataForm)
  } else {
    return api.saveStation(dataForm)
  }
}

const onShowErrorMessage = (msg) => {
  ElMessage({
    message: msg,
    type: 'error',
    duration: 1500
  })
}

// 通过省市区id,得到省市区名称
const onGetAreaName = () => {
  onGetProvinceName() // 保存省名字
  onGetCityName() // 保存市名字
  onGetDistrictName() // 保存区名字
}
const onGetProvinceName = () => {
  for (let i = 0; i < provinceList.length; i++) {
    if (provinceList[i].areaId === dataForm.provinceId) {
      // 将省名字保存起来
      dataForm.province = provinceList[i].areaName
    }
  }
}

const onGetCityName = () => {
  for (let i = 0; i < cityList.length; i++) {
    if (cityList[i].areaId === dataForm.cityId) {
      // 将市名字保存起来
      dataForm.city = cityList[i].areaName
    }
  }
}

const onGetDistrictName = () => {
  for (let i = 0; i < areaList.length; i++) {
    if (areaList[i].areaId === dataForm.areaId) {
      // 将市名字保存起来
      dataForm.area = areaList[i].areaName
    }
  }
}

// 腾讯地图
const tmapRef = ref(null)
const latLng = ref(null)
const onMapLocation = (isTrue) => {
  let address = ''
  const { provinceId, province, cityId, city, areaId, area, addr } = dataForm
  if (isTrue) {
    // 选择省市区时，定位地图
    if (provinceId) {
      address = province
      tmapRef.value.onSetZoom(6)
      if (cityId) {
        address = address + city
        tmapRef.value.onSetZoom(10)
        if (areaId) {
          address = address + area
          tmapRef.value.onSetZoom(18)
          if (addr) {
            // 详细地址
            address = address + addr
            tmapRef.value.onSetZoom(18)
          }
        }
      }
    }
    if (address) {
      tmapRef.value.onGetLocation(address).then(res => {
        onChangeLatLng(res)
      })
    }
  } else {
    if (!provinceId || !cityId || !areaId) {
      dataForm.detailAddress = null
      ElMessage({
        message: $t('admin.selePCD'),
        type: 'error',
        duration: 1000
      })
      return
    }
    tmapRef.value.onGetAddress(latLng.value).then(res => {
      dataForm.detailAddress = res.formatted_addresses?.recommend || res.address
    })
    tmapRef.value.onSetZoom(18)
  }
}

// 修改经纬度
const onChangeLatLng = (latLngInfo) => {
  const { lng, lat } = latLngInfo
  latLng.value = latLngInfo
  dataForm.lng = lng
  dataForm.lat = lat
}
const onHandleArr = (arr, data) => {
  arr.length = 0
  arr.push(...data)
}

const onHandleDataForm = (data) => {
  dataForm.stationId = data.stationId
  dataForm.stationName = data.stationName
  dataForm.imgUrl = data.imgUrl
  dataForm.mobilePrefix = data.mobilePrefix
  dataForm.mobile = data.mobile
  dataForm.startTime = data.startTime
  dataForm.endTime = data.endTime
  dataForm.status = data.status
  dataForm.provinceId = data.provinceId
  dataForm.province = data.province
  dataForm.cityId = data.cityId
  dataForm.city = data.city
  dataForm.areaId = data.areaId
  dataForm.area = data.area
  dataForm.addr = data.addr
  dataForm.lng = data.lng
  dataForm.lat = data.lat
  dataForm.timeDateModeVO = data.timeDateModeVO
  dataForm.stockMode = data.stockMode
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.page-station-add-or-update {
  .map {
    width: 100%;
    height: 500px;
  }
  .area-select {
    display: flex;
  }
  .stationName :deep(.el-input__inner) {
    padding-right: 45px !important;
  }
  .addr :deep(.el-input__inner) {
    padding-right: 55px;
  }
}
</style>
