<script lang="ts" setup>
import { addSiteAPI, getAllOperatorRegionAPI, updateSiteAPI } from '@/api/operator'
import { useAppStore, useMap, useOperatorStore } from '@/store'
import { systemInfo } from '@/utils/systemInfo'

definePage({
  style: {
    navigationStyle: 'custom',
  },
})

const mapStore = useMap()
const formRef = ref(null)
const operatorStore = useOperatorStore()
const operatorAllList = ref<any>([])
const regionAllList = ref<any>([])
const siteTypeList = ref<any>([])
const appStore = useAppStore()
const paging = ref<any>(null)
const btnConfig = reactive({
  loading: false,
  loadingText: '提交中...',
})
const formData = ref<any>({
  siteId: undefined,
  operatorId: undefined,
  siteName: undefined,
  regionId: undefined,
  siteType: undefined,
  sitePolygon: {
    type: 'polygon',
    coordinates: [],
  },
})

const rules = {
  'siteName': {
    type: 'string',
    required: true,
    message: '请输入站点名称',
    trigger: ['blur'],
  },
  'operatorId': {
    type: 'string',
    required: true,
    message: '请选择运营商',
    trigger: ['change', 'blur'],
  },
  'regionId': {
    type: 'string',
    required: true,
    message: '请选择运营区域',
    trigger: ['change', 'blur'],
  },
  'siteType': {
    type: 'string',
    required: true,
    message: '请选择区域类型',
    trigger: ['change', 'blur'],
  },
  'sitePolygon.coordinates': {
    validator: (rule, value, callback) => {
      if (!value || value.length <= 0) {
        return false
      }
      return true
    },
    message: '请绘制地图',
    trigger: ['change'],
  },
}
const labelStyle = computed(() => {
  return {
    padding: '0 5px 0 5px',
    color: '#333333',
    fontSize: '14px',
    fontWeight: 'normal',
    lineHeight: '32px',
  }
})

// 返回
function handleBack() {
  uni.navigateBack()
}

// 获取所有运营区域
async function getAllOperatorRegion() {
  try {
    const res = await getAllOperatorRegionAPI()
    if (res) {
      regionAllList.value = res.map((it: any) => {
        return {
          text: it.regionName,
          value: it.regionId,
          regionPolygon: it.regionPolygon,
        }
      })

      // 赋值
      if (formData.value.regionId) {
        const region = regionAllList.value.find((it: any) => it.value === formData.value.regionId)?.regionPolygon
        const { coordinates } = region
        mapStore.setCoordinates(coordinates)
      }
    }
  }
  catch (err) {
    console.error(err)
  }
}
// 获取运营商列表
async function getOperatorList() {
  operatorAllList.value = await operatorStore.getOperatorList(true)
  siteTypeList.value = appStore.getDictByCode('siteType')
}

// 获取区域列表
function regionChange(regionId: any) {
  const region = regionAllList.value.find(it => it.value === regionId)
  if (region) {
    const { coordinates } = region.regionPolygon
    mapStore.setCoordinates(coordinates)
  }
}

// 绘制地图
function handleMap() {
  console.log('handleMap')
  if (!mapStore.coordinates || mapStore.coordinates.length === 0) {
    return uni.showToast({
      title: '请选择运营区域',
      icon: 'none',
    })
  }
  uni.navigateTo({
    url: '/pages-sub/common/mapPlotting',
  })
}

// 提交
async function handleComplete() {
  if (mapStore?.sites.length > 0) {
    const list = mapStore.sites
    list.push(list[0])
    formData.value.sitePolygon.coordinates = list
  }

  btnConfig.loading = true
  try {
    const status = await formRef.value.validate()

    if (status) {
      console.log(formData.value)

      if (formData.value.siteId) {
        await updateSiteAPI(formData.value)
      }
      else {
        await addSiteAPI(formData.value)
      }
      mapStore.clearPoints()
      uni.showToast({
        title: formData.value.siteId ? '保存成功' : '新增成功',
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  }
  catch (err) {
    console.error('表单提交异常')
  }
  finally {
    btnConfig.loading = false
  }
}

onLoad((options) => {
  mapStore.clearPoints()
  if (options) {
    try {
      const data = JSON.parse(decodeURIComponent(options.data))
      const { siteId, siteName, regionId, sitePolygon, operatorId, siteType } = data
      if (siteId) {
        formData.value = {
          siteId,
          siteName,
          regionId,
          sitePolygon,
          operatorId,
          siteType: siteType.toString(),
        }

        const { coordinates } = sitePolygon
        coordinates.pop()
        mapStore.setSites(coordinates)
        console.log(coordinates, '-------site')
      }
    }
    catch {
      console.error('页面传参异常')
    }
  }
  getOperatorList()
  getAllOperatorRegion()
})
</script>

<template>
  <z-paging
    ref="paging"
    bg-color="#f9f9f9"
  >
    <template #top>
      <view class="custom_navbar" :style="{ height: `${systemInfo.statusBarHeight + 44}px` }">
        <view class="back_bar">
          <uv-icon name="arrow-left" color="white" size="24" @click="handleBack" />
          <text class="text">站点管理</text>
        </view>
      </view>
    </template>

    <view class="container">
      <uv-form
        ref="formRef"
        label-position="top"
        :model="formData"
        :rules="rules"
        label-width="150"
        :label-style="labelStyle"
      >
        <view class="card_box">
          <uv-form-item label="站点名称" prop="siteName" required>
            <uv-input v-model="formData.siteName" placeholder="请输入站点名称" border="surround" />
          </uv-form-item>
          <uv-form-item label="运营商" prop="operatorId" required>
            <uni-data-select
              v-model="formData.operatorId"
              :localdata="operatorAllList"
              placeholder="请选择运营商"
              clear
            />
          </uv-form-item>
          <uv-form-item label="运营区域" prop="regionId" required>
            <uni-data-select
              v-model="formData.regionId"
              :localdata="regionAllList"
              placeholder="请选择运营区域"
              clear
              @change="regionChange"
            />
          </uv-form-item>
          <uv-form-item label="区域类型" prop="siteType" required>
            <uv-radio-group v-model="formData.siteType">
              <uv-radio
                v-for="(item) in siteTypeList"
                :key="item.dicValueId"
                :custom-style="{ margin: '8px' }"
                :label="item.dicValueName"
                :name="item.dicValue"
              />
            </uv-radio-group>
          </uv-form-item>
        </view>
        <view class="card_box">
          <uv-form-item label="区域地图" prop="sitePolygon.coordinates" required>
            <view class="row">
              <uv-tags
                :text="mapStore.sites.length > 0 ? '已绘制' : '未绘制'"
                :type="mapStore.sites.length > 0 ? 'success' : 'warning'"
              />
              <view class="row_icon">
                <uv-text
                  suffix-icon="arrow-right"
                  icon-style="font-size: 26rpx"
                  :text="mapStore.sites.length > 0 ? '编辑地图' : '绘制地图'"
                  color="#1488f5"
                  @click="handleMap"
                />
              </view>
            </view>
          </uv-form-item>
        </view>
      </uv-form>
    </view>

    <template #bottom>
      <view class="bottom-button-zaping">
        <uv-button
          type="primary"
          :text="formData.siteId ? '保存' : '新增'"
          :loading="btnConfig.loading"
          :loading-text="btnConfig.loadingText"
          :custom-style="{
            backgroundImage: `linear-gradient(135deg, #1089FF 0%, #0F5BFF 100%)`,
            borderRadius: '28rpx',
            height: '100rpx',
          }"
          :custom-text-style="{
            fontSize: '32rpx',
            marginLeft: '8rpx',
          }"
          @click="handleComplete"
        />
      </view>
    </template>
  </z-paging>
</template>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  width: calc(100% - 40rpx);

  .card_box {
    padding: 30rpx 20rpx;
    width: calc(100% - 40rpx);
    background: #ffffff;
    border-radius: 26rpx;
    margin-bottom: 30rpx;
  }

  .row {
    display: flex;
    width: 100%;
    align-items: center;
    justify-content: space-between;

    .row_icon {
      width: 150rpx;
    }
  }
}

.custom_navbar {
  width: 100%;
  position: relative;
  background-color: #0f73ff;

  .back_bar {
    display: flex;
    align-items: center;
    position: absolute;
    bottom: 25rpx;
    left: 30rpx;

    .text {
      font-family: SourceHanSansCN-Medium;
      font-size: 34rpx;
      color: white;
      letter-spacing: 0;
      font-weight: 500;
    }
  }
}

::v-deep .uv-form-item__body__left__content__required {
  line-height: 30px !important;
}
::v-deep .uni-select {
  min-height: 80rpx;
}
::v-deep .uni-select__input-placeholder {
  font-size: 28rpx;
  color: #c1c5cd;
}
</style>
