<template>
  <el-dialog :title="mode==='add' ? '添加' : '编辑'" :visible.sync="visible" width="600px" 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="form.serviceCityPid" placeholder="请选择服务城市" @change="handleProvinceChange">
          <el-option
            v-for="item in selectAreaShenDataList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="服务地区" prop="serviceCityIds">
        <el-select v-model="selectedAreas" multiple placeholder="请选择服务地区" :disabled="!form.serviceCityPid">
          <el-option
            v-for="item in selectAreaShiDataList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="技能" prop="skillIds">
        <el-select v-model="selectedSkills" multiple placeholder="请选择技能">
          <el-option
            v-for="item in skillList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="当前佣金" prop="commission">
        <el-input v-model="form.commission" placeholder="0.00">
          <template slot="prepend">￥</template>
        </el-input>
      </el-form-item>

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

      <el-form-item label="创建时间" v-if="form.createdAt">
        <el-input v-model="createdAtDisplay" disabled />
      </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 { selectAreaList } from "@/api/system/WorkerApply"

export default {
  name: "UserEditDialog",
  props: {
    visible: Boolean,
    user: Object,
    mode: String // 'add' or 'edit'
  },
  data() {
    return {
      form: {
        id: undefined,
        name: undefined,
        phone: undefined,
        avatar: undefined,
        prohibitTime: undefined,
        prohibitTimeNum: 0,
        serviceCityPid: undefined,
        serviceCityIds: undefined,
        skillIds: undefined,
        commission: undefined,
        status: 1,
        createdAt: undefined
      },
      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" }
        ]
      },
      selectAreaShenDataList: [],
      selectAreaShiDataList: [],
      selectedAreas: [],
      selectedSkills: [],
      skillList: [
        { id: 1, title: '水电工' },
        { id: 2, title: '油工师傅' },
        { id: 3, title: '改造维修' },
        { id: 4, title: '工程施工' }
      ]
    }
  },
  computed: {
    createdAtDisplay() {
      if (this.form.createdAt) {
        return this.parseTime(this.form.createdAt, '{y}-{m}-{d} {h}:{i}:{s}')
      }
      return ''
    }
  },
  watch: {
    user: {
      handler(val) {
        if (val) {
          this.form = { ...val }
          // 确保status是数字类型
          if (typeof this.form.status === 'string') {
            this.form.status = parseInt(this.form.status)
          }
          // 处理已选择的地区
          if (this.form.serviceCityIds) {
            this.selectedAreas = typeof this.form.serviceCityIds === 'string' 
              ? this.form.serviceCityIds.split(',').map(Number).filter(n => !isNaN(n))
              : this.form.serviceCityIds
          }
          // 处理已选择的技能
          if (this.form.skillIds) {
            this.selectedSkills = typeof this.form.skillIds === 'string'
              ? this.form.skillIds.split(',').map(Number).filter(n => !isNaN(n))
              : this.form.skillIds
          }
          // 处理禁止接单时长
          if (this.form.prohibitTimeNum) {
            this.form.prohibitTimeNum = parseInt(this.form.prohibitTimeNum) || 0
          }
        }
      },
      immediate: true
    },
    visible(val) {
      if (val) {
        this.getShenDataList()
        if (this.form.serviceCityPid) {
          this.getShiDataList(this.form.serviceCityPid)
        }
      }
    },
    selectedAreas(val) {
      this.form.serviceCityIds = val.join(',')
    },
    selectedSkills(val) {
      this.form.skillIds = val.join(',')
    }
  },
  methods: {
    getShenDataList() {
      selectAreaList("100000").then(response => {
        this.selectAreaShenDataList = response.data || []
      }).catch(() => {
        // 如果接口失败，使用默认数据
        this.selectAreaShenDataList = [
          { id: "610100", title: "西安市" },
          { id: "610200", title: "铜川市" },
          { id: "610300", title: "宝鸡市" }
        ]
      })
    },
    getShiDataList(id) {
      selectAreaList(id).then(response => {
        this.selectAreaShiDataList = response.data || []
      }).catch(() => {
        // 如果接口失败，使用默认数据
        if (id === "610100") {
          this.selectAreaShiDataList = [
            { id: "610102", title: "新城区" },
            { id: "610103", title: "碑林区" },
            { id: "610104", title: "莲湖区" },
            { id: "610111", title: "灞桥区" },
            { id: "610112", title: "未央区" },
            { id: "610113", title: "雁塔区" },
            { id: "610114", title: "阎良区" },
            { id: "610115", title: "临潼区" },
            { id: "610116", title: "长安区" },
            { id: "610117", title: "高陵区" }
          ]
        }
      })
    },
    handleProvinceChange() {
      if (this.form.serviceCityPid) {
        this.getShiDataList(this.form.serviceCityPid)
        this.selectedAreas = []
        this.form.serviceCityIds = ''
      }
    },
    decreaseTime() {
      if (this.form.prohibitTimeNum > 0) {
        this.form.prohibitTimeNum--
      }
    },
    increaseTime() {
      this.form.prohibitTimeNum++
    },
    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/')
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return time_str
    },
    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)
        }
      })
    },
    resetForm() {
      // 重置表单但保留id
      const id = this.form.id
      const createdAt = this.form.createdAt
      this.$refs["form"].resetFields()
      this.selectedAreas = []
      this.selectedSkills = []
      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
      }
    }
  }
}
</script>

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

.time-input .el-input-number {
  margin: 0 5px;
}

.time-input .el-button {
  padding: 7px;
  min-width: 32px;
}

.el-select {
  width: 100%;
}

::v-deep .el-input-number .el-input__inner {
  text-align: center;
}

::v-deep .el-dialog__body {
  padding: 20px 20px 0;
}

::v-deep .el-form-item {
  margin-bottom: 18px;
}

::v-deep .el-input-group__prepend {
  padding: 0 10px;
}
</style> 