<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="650px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
<el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
    <el-form-item v-if="formData.root == 1" label="所属用户" prop="user_id">
    <el-select
        v-model="formData.user_id"
        remote
        filterable
        placeholder="请输入用户信息"
        :remote-method="queryUser"
        :loading="loading"
      >
      <el-option
        v-for="(item, index) in optionsData.user"
        :key="index"
        :label="item.userinfo"
        :value="item.id"
    />
      </el-select>
</el-form-item>
                <el-form-item label="土地名称" prop="title">
    <el-input v-model="formData.title" clearable placeholder="请输入土地名称" />
</el-form-item>
<el-form-item label="详细地址" prop="address">
    <el-input v-model="formData.address" clearable placeholder="请输入详细地址" />
</el-form-item>
                <el-form-item label="土地面积" prop="total_area">
    <el-input v-model="formData.total_area" clearable placeholder="请输入土地面积" />
</el-form-item>
                <!-- <el-form-item label="剩余面积" prop="residual_area">
    <el-input v-model="formData.residual_area" clearable disabled placeholder="请输入剩余面积" />
</el-form-item> -->

  <el-form-item
      label="省"
      :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
      prop="province_code"
  >
    <el-select
        v-model="formData.province_code"
        placeholder="请选择省"
        clearable
        @change="province_change"
        :style="{ width: '100%' }"
    >
      <el-option
          v-for="(item, index) in datas.provinceOptions"
          :key="index"
          :label="item.province_name"
          :value="item.province_code"
      ></el-option>
    </el-select>
  </el-form-item>
  <el-form-item
      label="市"
      :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
      prop="city_code"
  >
    <el-select
        v-model="formData.city_code"
        placeholder="请选择市"
        clearable
        @change="city_change"
        :style="{ width: '100%' }"
    >
      <el-option
          v-for="(item, index) in datas.cityOptions"
          :key="index"
          :label="item.city_name"
          :value="item.city_code"
      ></el-option>
    </el-select>
  </el-form-item>
  <el-form-item
      label="区"
      :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
      prop="county_code"
  >
    <el-select
        v-model="formData.county_code"
        placeholder="请选择区"
        clearable
        @change="area_change"
        :style="{ width: '100%' }"
    >
      <el-option
          v-for="(item, index) in datas.areaOptions"
          :key="index"
          :label="item.county_name"
          :value="item.county_code"
      ></el-option>
    </el-select>
  </el-form-item>
  <el-form-item
      label="镇"
      :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
      prop="town_code"
  >
    <el-select
        v-model="formData.town_code"
        placeholder="请选择镇"
        clearable
        @change="street_change"
        :style="{ width: '100%' }"
    >
      <el-option
          v-for="(item, index) in datas.streetOptions"
          :key="index"
          :label="item.town_name"
          :value="item.town_code"
      ></el-option>
    </el-select>
  </el-form-item>
  <el-form-item
      label="村"
      :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
      prop="village_code"
  >
    <el-select
        v-model="formData.village_code"
        placeholder="请选择村"
        clearable
        @change="village_change"
        :style="{ width: '100%' }"
    >
      <el-option
          v-for="(item, index) in datas.villageOptions"
          :key="index"
          :label="item.village_name"
          :value="item.village_code"
      ></el-option>
    </el-select>
  </el-form-item>
  <el-form-item
      label="队"
      :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]"
      prop="group_code"
  >
    <el-select
        v-model="formData.group_code"
        placeholder="请选择队"
        clearable
        :style="{ width: '100%' }"
    >
      <el-option
          v-for="(item, index) in datas.brigadeOptions"
          :key="index"
          :label="item.group_name"
          :value="item.id"
      ></el-option>
    </el-select>
  </el-form-item>
                <el-form-item label="土地负责人" prop="master_name">
    <el-input v-model="formData.master_name" clearable placeholder="请输入土地负责人" />
</el-form-item>
                <el-form-item label="负责人电话" prop="master_phone">
    <el-input v-model="formData.master_phone" clearable placeholder="请输入负责人电话" />
</el-form-item>
                <!-- <el-form-item label="土地图片" prop="pic">
    <material-picker v-model="formData.pic" :limit="4" />
</el-form-item> -->
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="landEdit">
import { useDictOptions } from '@/hooks/useDictOptions'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiLandAdd, apiLandEdit, apiLandDetail, getUserList, getUserInfo } from '@/api/land'
import {
  apiCityList,
  apiAreaList,
  apiStreetList,
  apiProvinceList,
  apiVillageList,
  apiBrigadeList,
} from "@/api/common";
import type { PropType } from 'vue'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

// 弹窗标题
const popupTitle = computed(() => {
  if (mode.value == 'edit') {
    getCityList();
    getAreaList();
    getStreetList();
    getVillageList();
    getBrigadeList();
  }
    return mode.value == 'edit' ? '编辑土地' : '新增土地'
})
// 表单数据
const formData = reactive({
    id: '',
    user_id: '',
    root: 0,
    title: '',
    total_area: '',
    residual_area: '',
    province_code: '',
    province_name: '',
    city_code: '',
    city_name: '',
    county_code: '',
    county_name: '',
    town_code: '',
    town_name: '',
    village_code: '',
    village_name: '',
    group_code: '',
    group_name: '',
    master_name: '',
    master_phone: '',
    address: '',
    pic: '',
    mode: mode.value
})

// 表单验证
const formRules = reactive<any>({
    title: [{
        required: true,
        message: '请输入土地名称',
        trigger: ['blur']
    }],
    address: [{
        required: true,
        message: '请输入详细地址',
        trigger: ['blur']
    }],
    master_name: [{
        required: true,
        message: '请输入土地负责人',
        trigger: ['blur']
    }],
    master_phone: [{
        required: true,
        message: '请输入负责人电话',
        trigger: ['blur']
    }]
})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
            if (key == 'pic') {
                formData[key] = ''
            }
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiLandDetail({
        id: row.id
    })
    setFormData(data)
}

const { optionsData } = useDictOptions<{
    user: any[]
}>({
    user: {
        api: getUserList
    }
})

const loading = ref(false)

const queryUser = async (query: string) => {
    loading.value = true
    const userList = await getUserList({
        keyword: query ?? ''
    })
    optionsData.user = userList
    loading.value = false
}

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData,  }
    mode.value == 'edit' 
        ? await apiLandEdit(data) 
        : await apiLandAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
    getUserInfo()
        .then((res: any) => {
            const root = res.user.root ?? 0
            formData.root = root
        })
        .catch((err: any) => {
            console.log('err', err)
        })
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

const datas = reactive({
  provinceOptions: [],
  cityOptions: [],
  areaOptions: [],
  streetOptions: [],
  villageOptions: [],
  brigadeOptions: [],
});
function province_change(value: string) {
  getCityList();
  // 给省名称赋值
  datas['provinceOptions'].forEach((item: any) =>{
    if(item.province_code == value) {
      formData.province_name = item.province_name
    }
  })
}
function city_change(value: string) {
  getAreaList();
}
function area_change(value: string) {
  getStreetList();
}
function street_change(value: string) {
  getVillageList();
}
function village_change(value: string) {
  getBrigadeList();
}
// function brigade_change(value: string) {
//     formData.brigade = value
// }
const getProvinceList = async () => {
  const data = await apiProvinceList({});
  datas["provinceOptions"] = data;
};
const getCityList = async () => {
  const data = await apiCityList({ city: formData.province_code });
  datas["cityOptions"] = data;
};
const getAreaList = async () => {
  const data = await apiAreaList({ area: formData.city_code });
  datas["areaOptions"] = data;
  // 市名称
  datas['cityOptions'].forEach((item: any) =>{
    if(item.city_code == formData.city_code) {
      formData.city_name = item.city_name
    }
  })
};
const getStreetList = async () => {
  const data = await apiStreetList({ street: formData.county_code });
  datas["streetOptions"] = data;
  // 区名称
  datas['areaOptions'].forEach((item: any) =>{
    if(item.county_code == formData.county_code) {
      formData.county_name = item.county_name
    }
  })
};
const getVillageList = async () => {
  const data = await apiVillageList({ village: formData.town_code });
  datas["villageOptions"] = data;
// 镇名称
  datas['streetOptions'].forEach((item: any) =>{
    if(item.town_code == formData.town_code) {
      formData.town_name = item.town_name
    }
  })
};
const getBrigadeList = async () => {
  const data = await apiBrigadeList();
  datas["brigadeOptions"] = data;
  // 镇名称
  datas['villageOptions'].forEach((item: any) =>{
    if(item.village_code == formData.village_code) {
      formData.village_name = item.village_name
    }
  })
};
getProvinceList(); // 初始化即请求省份数据

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
