<template>
  <el-dialog :title="mode==='add' ? '添加师傅' : '编辑师傅'" :visible.sync="visible" width="700px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="ID" v-if="form.id">
        <el-input v-model="form.id" disabled />
      </el-form-item>

      <el-form-item label="昵称" prop="name">
        <el-input v-model="form.name" placeholder="请输入昵称" />
      </el-form-item>

      <el-form-item label="电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入电话" />
      </el-form-item>

      <el-form-item label="头像" prop="avatar">
        <image-upload v-model="form.avatar" :limit="1"/>
      </el-form-item>

      <el-form-item label="禁止接单开始时间" prop="prohibitTime">
        <el-date-picker
          v-model="form.prohibitTime"
          type="datetime"
          placeholder="输入禁止开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="禁止接单时长" prop="prohibitTimeNum">
        <div class="time-input">
          <el-button icon="el-icon-minus" @click="decreaseTime" size="small"></el-button>
          <el-input-number
            v-model="form.prohibitTimeNum"
            :min="0"
            :controls="false"
            placeholder="0"
            style="width: 100px; text-align: center;" />
          <el-button icon="el-icon-plus" @click="increaseTime" size="small"></el-button>
          <span style="margin-left: 10px;">小时</span>
        </div>
      </el-form-item>

      <el-form-item label="服务城市" prop="serviceCityPid">
        <el-select
          v-model="selectedCity"
          placeholder="请选择服务城市"
          filterable
          clearable
          style="width: 100%"
          @change="handleCityChange">
          <el-option
            v-for="item in cityList"
            :key="item.id"
            :label="item.title"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="服务地区" prop="serviceCityIds">
        <el-select
          v-model="selectedAreas"
          placeholder="请选择服务地区"
          filterable
          multiple
          style="width: 100%"
          @change="handleAreaChange">
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.title"
            :value="item.id">
          </el-option>
        </el-select>
        <!-- 显示已选择的地区标签
        <div class="selected-tags" v-if="selectedAreas.length > 0">
          <el-tag
            v-for="areaId in selectedAreas"
            :key="areaId"
            closable
            @close="removeArea(areaId)"
            style="margin: 2px;">
            {{ getAreaName(areaId) }}
          </el-tag>
        </div> -->
      </el-form-item>

      <el-form-item label="技能" prop="skillIds">
        <div class="skill-selection">
          <el-select
            v-model="selectedSkills"
            multiple
            filterable
            placeholder="请选择技能"
            style="width: 100%"
            @change="handleSkillChange"
          >
            <el-option
              v-for="item in skillList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
          <!-- 显示已选择的技能标签
          <div class="selected-tags" v-if="selectedSkills.length > 0">
            <el-tag
              v-for="skillId in selectedSkills"
              :key="skillId"
              closable
              @close="removeSkill(skillId)"
              type="success"
              style="margin: 2px;"
            >
              {{ getSkillName(skillId) }}
            </el-tag>
          </div> -->
        </div>
      </el-form-item>

  

      <el-form-item label="状态">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="禁用">
        </el-switch>
      </el-form-item>

    
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="resetForm">重置</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { datalist } from "@/api/system/DiyCity"
import { getSiteSkillList } from "@/api/system/SiteSkill"

export default {
  name: "UserEditDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    user: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      form: {
        id: null,
        name: undefined,
        phone: undefined,
        avatar: undefined,
        prohibitTime: undefined,
        prohibitTimeNum: 0,
        serviceCityPid: undefined,
        serviceCityIds: undefined,
        skillIds: undefined,
        commission: undefined,
        status: 1,
        createdAt: null
      },
      rules: {
        name: [
          { required: true, message: "昵称不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "电话不能为空", trigger: "blur" }
        ],
        serviceCityPid: [
          { required: true, message: "服务城市不能为空", trigger: "change" }
        ],
        serviceCityIds: [
          { required: true, message: "服务地区不能为空", trigger: "change" }
        ],
        skillIds: [
          { required: true, message: "技能不能为空", trigger: "change" }
        ]
      },
      // 城市相关数据
      cityList: [],
      selectedCity: undefined,
      cityNameCache: {},
      
      // 地区相关数据
      areaList: [],
      selectedAreas: [],
      areaNameCache: {},
      
      // 技能相关数据
      skillList: [],
      selectedSkills: [],
      skillNameCache: {},
      
      // 标记是否正在初始化数据
      isInitializing: false
    }
  },
  watch: {
    user: {
      handler(val) {
        if (val) {
          console.log('UserEditDialog - 接收到用户数据:', val);
          this.form = { ...val }
          
          // 确保status是数字类型
          if (typeof this.form.status === 'string') {
            this.form.status = parseInt(this.form.status)
          }
          
          // 处理禁止接单时长
          if (this.form.prohibitTimeNum) {
            this.form.prohibitTimeNum = parseInt(this.form.prohibitTimeNum) || 0
          }
          
          // 清除验证错误
          this.$nextTick(() => {
            if (this.$refs["form"]) {
              this.$refs["form"].clearValidate();
            }
          });
        }
      },
      immediate: true
    },
    visible(val) {
      if (val) {
        console.log('UserEditDialog - 弹窗打开，开始加载数据');
        this.isInitializing = true; // 设置初始化标记
        // 先加载基础数据，然后处理已选择的数据
        Promise.all([
          this.loadCityList(),
          this.loadSkillList()
        ]).then(() => {
          console.log('UserEditDialog - 基础数据加载完成，开始处理已选择的数据');
          // 处理服务城市ID
          this.processSelectedCity();
          // 处理技能ID
          this.processSelectedSkills();
          
          // 如果有选中的城市，加载对应的地区数据
          if (this.selectedCity) {
            this.loadAreaList().then(() => {
              // 处理服务地区ID
              this.processSelectedAreas();
              this.isInitializing = false; // 初始化完成
            });
          } else {
            this.isInitializing = false; // 初始化完成
          }
        }).catch(() => {
          this.isInitializing = false; // 即使出错也要重置标记
        });
      } else {
        // 弹窗关闭时重置数据
        this.resetDialogData();
      }
    },
    selectedCity(val) {
      this.form.serviceCityPid = val;
      this.updateCityNameCache();
      // 只有在用户主动选择时才重新加载地区列表（非初始化状态）
      if (!this.isInitializing && this.visible && this.cityList.length > 0) {
        // 清空当前选中的地区，因为城市变化了
        this.selectedAreas = [];
        this.areaList = [];
        this.loadAreaList();
      }
    },
    selectedAreas(val) {
      this.form.serviceCityIds = val.join(',');
      this.updateAreaNameCache();
    },
    selectedSkills(val) {
      this.form.skillIds = val.join(',');
      this.updateSkillNameCache();
    }
  },
  methods: {
    // 加载城市列表
    loadCityList() {
      console.log('UserEditDialog - 开始加载城市列表');
      const queryParams = {
        parentId: 0 // 查询一级城市（省份）
      }
      return datalist(queryParams).then(response => {
        console.log('UserEditDialog - 获取城市列表成功:', response);
        if (response.code === 200) {
          // AjaxResult.success()方法返回的数据在data字段中
          this.cityList = response.data || [];
          console.log('UserEditDialog - 城市列表:', this.cityList);
          this.updateCityNameCache();
        } else {
          console.warn('UserEditDialog - 获取城市列表失败，使用默认数据');
          this.cityList = [
            { id: 1, title: '陕西省' },
            { id: 27, title: '上海市' },
            { id: 44, title: '湖南省' },
            { id: 52, title: '安徽省' }
          ];
        }
        return response;
      }).catch((error) => {
        console.error('UserEditDialog - 获取城市列表异常:', error);
        this.cityList = [
          { id: 1, title: '陕西省' },
          { id: 27, title: '上海市' },
          { id: 44, title: '湖南省' },
          { id: 52, title: '安徽省' }
        ];
        return Promise.reject(error);
      });
    },
    
    // 加载地区列表
    loadAreaList() {
      console.log('UserEditDialog - 开始加载地区列表，选中的城市:', this.selectedCity);
      this.areaList = [];
      this.areaNameCache = {};
      
      if (!this.selectedCity) {
        return Promise.resolve(); // 如果没有选中的城市，直接返回
      }
      
      // 为选中的城市加载地区数据
      const queryParams = {
        parentId: this.selectedCity // 根据城市ID查询下级地区
      }
      return datalist(queryParams).then(response => {
        console.log(`UserEditDialog - 获取城市${this.selectedCity}的地区数据成功:`, response);
        if (response.code === 200) {
          // AjaxResult.success()方法返回的数据在data字段中
          this.areaList = response.data || [];
        }
        console.log('UserEditDialog - 地区数据加载完成，地区列表:', this.areaList);
        this.updateAreaNameCache();
        return response;
      }).catch((error) => {
        console.error(`UserEditDialog - 获取城市${this.selectedCity}的地区数据失败:`, error);
        // 使用默认数据
        let defaultAreas = [];
        if (this.selectedCity === 1) {
          defaultAreas = [
            { id: 2, title: '新城区' },
            { id: 5, title: '碑林区' },
            { id: 7, title: '莲湖区' },
            { id: 10, title: '灞桥区' },
            { id: 11, title: '未央区' },
            { id: 12, title: '雁塔区' },
            { id: 13, title: '阎良区' },
            { id: 14, title: '临潼区' },
            { id: 15, title: '长安区' },
            { id: 16, title: '高陵区' },
            { id: 17, title: '鄠邑区' }
          ];
        } else if (this.selectedCity === 52) {
          defaultAreas = [
            { id: 53, title: '瑶海区' },
            { id: 54, title: '庐阳区' },
            { id: 55, title: '蜀山区' },
            { id: 56, title: '包河区' },
            { id: 57, title: '经开区' },
            { id: 58, title: '高新区' }
          ];
        }
        
        this.areaList = defaultAreas;
        this.updateAreaNameCache();
        return Promise.resolve(); // 即使加载失败，也返回一个已完成的Promise
      });
    },
    
    // 加载技能列表
    loadSkillList() {
      console.log('UserEditDialog - 开始加载技能列表');
      return getSiteSkillList().then(response => {
        console.log('UserEditDialog - 获取技能列表成功:', response);
        if (response.code === 200) {
          this.skillList = response.data || [];
          console.log('UserEditDialog - 技能列表:', this.skillList);
          this.updateSkillNameCache();
        } else {
          console.warn('UserEditDialog - 获取技能列表失败，使用默认数据');
          this.skillList = [
            { id: 1, title: '水电工' },
            { id: 2, title: '油工师傅' },
            { id: 3, title: '改造维修' },
            { id: 4, title: '工程施工' }
          ];
        }
        return response;
      }).catch((error) => {
        console.error('UserEditDialog - 获取技能列表异常:', error);
        this.skillList = [
          { id: 1, title: '水电工' },
          { id: 2, title: '油工师傅' },
          { id: 3, title: '改造维修' },
          { id: 4, title: '工程施工' }
        ];
        return Promise.reject(error);
      });
    },
    
    // 处理已选择的城市
    processSelectedCity() {
      console.log('开始处理服务城市数据:', this.form.serviceCityPid, '类型:', typeof this.form.serviceCityPid);
      this.selectedCity = undefined; // 先清空
      
      if (this.form.serviceCityPid) {
        try {
          let cityId = this.form.serviceCityPid;
          if (typeof this.form.serviceCityPid === 'string') {
            if (this.form.serviceCityPid.startsWith('[') && this.form.serviceCityPid.endsWith(']')) {
              const parsed = JSON.parse(this.form.serviceCityPid);
              cityId = Array.isArray(parsed) ? parsed[0] : parsed;
            } else if (this.form.serviceCityPid.includes(',')) {
              // 如果是逗号分隔的字符串，取第一个
              cityId = this.form.serviceCityPid.split(',')[0].trim();
            } else {
              cityId = this.form.serviceCityPid.trim();
            }
          } else if (Array.isArray(this.form.serviceCityPid)) {
            cityId = this.form.serviceCityPid[0];
          } else if (typeof this.form.serviceCityPid === 'number') {
            cityId = this.form.serviceCityPid;
          }
          
          // 转换为数字并验证
          const parsedId = parseInt(cityId);
          if (!isNaN(parsedId) && parsedId > 0) {
            this.selectedCity = parsedId;
            console.log('解析后的服务城市:', this.selectedCity);
            
            // 更新缓存
            this.$nextTick(() => {
              this.updateCityNameCache();
            });
          }
        } catch (error) {
          console.error('解析服务城市数据失败:', error);
          this.selectedCity = undefined;
        }
      }
    },
    
    // 处理已选择的地区
    processSelectedAreas() {
      console.log('开始处理服务地区数据:', this.form.serviceCityIds, '类型:', typeof this.form.serviceCityIds);
      this.selectedAreas = []; // 先清空
      
      if (this.form.serviceCityIds) {
        try {
          let areaIds = [];
          if (typeof this.form.serviceCityIds === 'string') {
            if (this.form.serviceCityIds.startsWith('[') && this.form.serviceCityIds.endsWith(']')) {
              areaIds = JSON.parse(this.form.serviceCityIds);
            } else {
              areaIds = this.form.serviceCityIds.split(',').map(id => id.trim()).filter(id => id);
            }
          } else if (Array.isArray(this.form.serviceCityIds)) {
            areaIds = this.form.serviceCityIds;
          } else if (typeof this.form.serviceCityIds === 'number') {
            areaIds = [this.form.serviceCityIds];
          }
          
          // 转换为数字并过滤无效值
          this.selectedAreas = areaIds.map(id => parseInt(id)).filter(id => !isNaN(id) && id > 0);
          console.log('解析后的服务地区:', this.selectedAreas);
          
          // 更新缓存
          this.$nextTick(() => {
            this.updateAreaNameCache();
          });
        } catch (error) {
          console.error('解析服务地区数据失败:', error);
          this.selectedAreas = [];
        }
      }
    },
    
    // 处理已选择的技能
    processSelectedSkills() {
      console.log('开始处理技能数据:', this.form.skillIds, '类型:', typeof this.form.skillIds);
      this.selectedSkills = []; // 先清空
      
      if (this.form.skillIds) {
        try {
          let skillIds = [];
          if (typeof this.form.skillIds === 'string') {
            if (this.form.skillIds.startsWith('[') && this.form.skillIds.endsWith(']')) {
              skillIds = JSON.parse(this.form.skillIds);
            } else {
              skillIds = this.form.skillIds.split(',').map(id => id.trim()).filter(id => id);
            }
          } else if (Array.isArray(this.form.skillIds)) {
            skillIds = this.form.skillIds;
          } else if (typeof this.form.skillIds === 'number') {
            skillIds = [this.form.skillIds];
          }
          
          // 转换为数字并过滤无效值
          this.selectedSkills = skillIds.map(id => parseInt(id)).filter(id => !isNaN(id) && id > 0);
          console.log('解析后的技能:', this.selectedSkills);
          
          // 更新缓存
          this.$nextTick(() => {
            this.updateSkillNameCache();
          });
        } catch (error) {
          console.error('解析技能数据失败:', error);
          this.selectedSkills = [];
        }
      }
    },
    
    // 更新城市名称缓存
    updateCityNameCache() {
      console.log('更新城市名称缓存，已选择城市:', this.selectedCity, '城市列表:', this.cityList);
      this.cityNameCache = {};
      if (this.selectedCity) {
        const city = this.cityList.find(item => item.id === this.selectedCity);
        if (city) {
          this.cityNameCache[this.selectedCity] = city.title;
        } else {
          console.warn('未找到城市ID:', this.selectedCity, '对应的名称');
        }
      }
      console.log('城市名称缓存:', this.cityNameCache);
    },
    
    // 更新地区名称缓存
    updateAreaNameCache() {
      console.log('更新地区名称缓存，已选择地区:', this.selectedAreas, '地区列表:', this.areaList);
      this.areaNameCache = {};
      this.selectedAreas.forEach(areaId => {
        const area = this.areaList.find(item => item.id === areaId);
        if (area) {
          this.areaNameCache[areaId] = area.title;
        } else {
          console.warn('未找到地区ID:', areaId, '对应的名称');
        }
      });
      console.log('地区名称缓存:', this.areaNameCache);
    },
    
    // 更新技能名称缓存
    updateSkillNameCache() {
      console.log('更新技能名称缓存，已选择技能:', this.selectedSkills, '技能列表:', this.skillList);
      this.skillNameCache = {};
      this.selectedSkills.forEach(skillId => {
        const skill = this.skillList.find(item => item.id === skillId);
        if (skill) {
          this.skillNameCache[skillId] = skill.title;
        } else {
          console.warn('未找到技能ID:', skillId, '对应的名称');
        }
      });
      console.log('技能名称缓存:', this.skillNameCache);
    },
    
    // 获取城市名称
    getCityName(cityId) {
      return this.cityNameCache[cityId] || this.cityList.find(item => item.id === cityId)?.title || cityId;
    },
    
    // 获取地区名称
    getAreaName(areaId) {
      return this.areaNameCache[areaId] || this.areaList.find(item => item.id === areaId)?.title || areaId;
    },
    
    // 获取技能名称
    getSkillName(skillId) {
      return this.skillNameCache[skillId] || this.skillList.find(item => item.id === skillId)?.title || skillId;
    },
    
    // 移除城市
    removeCity(cityId) {
      this.selectedCity = undefined;
    },
    
    // 移除地区
    removeArea(areaId) {
      const index = this.selectedAreas.indexOf(areaId);
      if (index > -1) {
        this.selectedAreas.splice(index, 1);
      }
    },
    
    // 移除技能
    removeSkill(skillId) {
      const index = this.selectedSkills.indexOf(skillId);
      if (index > -1) {
        this.selectedSkills.splice(index, 1);
      }
    },
    
    // 城市选择变化
    handleCityChange() {
      console.log('城市选择变化:', this.selectedCity);
      this.updateCityNameCache();
      
      // 清空当前选中的地区，因为城市变化了
      this.selectedAreas = [];
      this.areaList = [];
      
      // 重新加载地区列表
      if (this.selectedCity) {
        this.loadAreaList();
      }
    },
    
    // 地区选择变化
    handleAreaChange() {
      console.log('地区选择变化:', this.selectedAreas);
      this.updateAreaNameCache();
    },
    
    // 技能选择变化
    handleSkillChange() {
      console.log('技能选择变化:', this.selectedSkills);
      this.updateSkillNameCache();
    },
    
    // 减少时间
    decreaseTime() {
      if (this.form.prohibitTimeNum > 0) {
        this.form.prohibitTimeNum--;
      }
    },
    
    // 增加时间
    increaseTime() {
      this.form.prohibitTimeNum++;
    },
    
    // 提交表单
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保必要的字段有值
          const submitData = {
            ...this.form,
            type: '2', // 师傅类型
            status: this.form.status || 0,
            prohibitTimeNum: this.form.prohibitTimeNum || 0
          }
          this.$emit('confirm', submitData)
        } else {
          console.log('表单验证失败');
        }
      })
    },
    
    // 重置弹窗数据
    resetDialogData() {
      this.isInitializing = false;
      this.cityList = [];
      this.selectedCity = undefined;
      this.cityNameCache = {};
      this.areaList = [];
      this.selectedAreas = [];
      this.areaNameCache = {};
      this.skillList = [];
      this.selectedSkills = [];
      this.skillNameCache = {};
    },
    
    // 重置表单
    resetForm() {
      // 重置表单但保留id
      const id = this.form.id
      const createdAt = this.form.createdAt
      this.$refs["form"].resetFields()
      this.resetDialogData()
      this.form = {
        id: id,
        name: undefined,
        phone: undefined,
        avatar: undefined,
        prohibitTime: undefined,
        prohibitTimeNum: 0,
        serviceCityPid: undefined,
        serviceCityIds: undefined,
        skillIds: undefined,
        commission: undefined,
        status: 1,
        createdAt: createdAt
      }
      // 清除验证错误
      this.$nextTick(() => {
        if (this.$refs["form"]) {
          this.$refs["form"].clearValidate();
        }
      });
    }
  }
}
</script>

<style scoped>
.time-input {
  display: flex;
  align-items: center;
}

.selected-tags {
  margin-top: 8px;
  max-width: 100%;
  overflow: hidden;
}

.selected-tags .el-tag {
  margin: 2px;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
