<template>
  <el-dialog
    :title="isEdit ? '编辑目标设置' : '新增目标设置'"
    :visible="visible"
    width="1000px"
    :close-on-click-modal="false"
    @close="handleClose"
    @update:visible="handleVisibleChange"
  >
    <div class="dialog-contentnew">
      <el-form 
        :model="localFormData" 
        :rules="rules" 
        ref="formRef" 
        label-width="160px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="门店" prop="storeId">
              <el-select 
                v-model="localFormData.storeId" 
                placeholder="请选择门店"
                filterable
                style="width: 100%"
                :disabled="isEdit"
              >
                <el-option
                  v-for="store in storeList"
                  :key="store.id"
                  :label="store.dm"
                  :value="store.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="月份" prop="month">
              <el-date-picker
                v-model="localFormData.month"
                type="month"
                placeholder="选择月份"
                format="yyyyMM"
                value-format="yyyyMM"
                style="width: 100%"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">部门信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="事业部" prop="businessUnit">
              <el-select 
                v-model="localFormData.businessUnit" 
                placeholder="请选择事业部"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in businessUnitOptions"
                  :key="item.id"
                  :label="item.fullName"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.fullName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.enCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="科技部" prop="techDepartment">
              <el-select 
                v-model="localFormData.techDepartment" 
                placeholder="请选择科技部"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in techDepartmentOptions"
                  :key="item.id"
                  :label="item.fullName"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.fullName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.enCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="教育部" prop="educationDepartment">
              <el-select 
                v-model="localFormData.educationDepartment" 
                placeholder="请选择教育部"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in educationDepartmentOptions"
                  :key="item.id"
                  :label="item.fullName"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.fullName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.enCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="大项目部" prop="majorProjectDepartment">
              <el-select 
                v-model="localFormData.majorProjectDepartment" 
                placeholder="请选择大项目部"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in majorProjectDepartmentOptions"
                  :key="item.id"
                  :label="item.fullName"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.fullName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.enCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">部门目标</el-divider>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="事业部目标" prop="businessUnitTarget">
              <el-input 
                v-model.number="localFormData.businessUnitTarget" 
                placeholder="请输入事业部目标"
                type="number"
                step="0.01"
                min="0"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="科技部目标" prop="techDepartmentTarget">
              <el-input 
                v-model.number="localFormData.techDepartmentTarget" 
                placeholder="请输入科技部目标"
                type="number"
                step="0.01"
                min="0"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="教育部目标" prop="educationDepartmentTarget">
              <el-input 
                v-model.number="localFormData.educationDepartmentTarget" 
                placeholder="请输入教育部目标"
                type="number"
                step="0.01"
                min="0"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="大项目部目标" prop="majorProjectDepartmentTarget">
              <el-input 
                v-model.number="localFormData.majorProjectDepartmentTarget" 
                placeholder="请输入大项目部目标"
                type="number"
                step="0.01"
                min="0"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">部门负责人</el-divider>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="事业部总经理" prop="businessUnitGeneralManager">
              <el-select 
                v-model="localFormData.businessUnitGeneralManager" 
                placeholder="请选择事业部总经理"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="user in managerList"
                  :key="user.id"
                  :label="`${user.realName} (${user.gw || '无岗位'})`"
                  :value="user.id"
                >
                  <span style="float: left">{{ user.realName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ user.gw || '无岗位' }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="事业部经理" prop="businessUnitManager">
              <el-select 
                v-model="localFormData.businessUnitManager" 
                placeholder="请选择事业部经理"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="user in managerList"
                  :key="user.id"
                  :label="`${user.realName} (${user.gw || '无岗位'})`"
                  :value="user.id"
                >
                  <span style="float: left">{{ user.realName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ user.gw || '无岗位' }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">门店业绩目标</el-divider>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="门店业绩目标" prop="storeTarget">
              <el-input 
                v-model.number="localFormData.storeTarget" 
                placeholder="请输入门店业绩目标"
                type="number"
                step="0.01"
                min="0"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="门店生命线" prop="storeLifeline">
              <el-input 
                v-model.number="localFormData.storeLifeline" 
                placeholder="请输入门店生命线"
                type="number"
                step="0.01"
                min="0"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="门店消耗目标" prop="storeConsumeTarget">
              <el-input 
                v-model.number="localFormData.storeConsumeTarget" 
                placeholder="请输入门店消耗目标"
                type="number"
                step="0.01"
                min="0"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="门店项目数目标" prop="storeProjectTarget">
              <el-input 
                v-model.number="localFormData.storeProjectTarget" 
                placeholder="请输入门店项目数目标"
                type="number"
                step="0.01"
                min="0"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">人员目标</el-divider>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="门店人头目标" prop="storeHeadcountTarget">
              <el-input 
                v-model.number="localFormData.storeHeadcountTarget" 
                placeholder="请输入门店人头目标"
                type="number"
                step="1"
                min="0"
              >
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="店助人头目标数阶段一" prop="assistantHeadcountTargetStage1">
              <el-input 
                v-model.number="localFormData.assistantHeadcountTargetStage1" 
                placeholder="请输入店助人头目标数阶段一"
                type="number"
                step="1"
                min="0"
              >
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="店助人头目标数阶段二" prop="assistantHeadcountTargetStage2">
              <el-input 
                v-model.number="localFormData.assistantHeadcountTargetStage2" 
                placeholder="请输入店助人头目标数阶段二"
                type="number"
                step="1"
                min="0"
              >
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit"
        :loading="loading"
      >
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { lqmdtargetApi } from '@/api/extend/lqmdtarget'


export default {
  name: 'EditDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => null
    },
    storeList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      localFormData: {
        storeId: '',
        month: '',
        businessUnit: '',
        techDepartment: '',
        educationDepartment: '',
        majorProjectDepartment: '',
        businessUnitTarget: 0,
        techDepartmentTarget: 0,
        educationDepartmentTarget: 0,
        businessUnitGeneralManager: '',
        businessUnitManager: '',
        storeTarget: 0,
        storeLifeline: 0,
        storeConsumeTarget: 0,
        storeProjectTarget: 0,
        storeHeadcountTarget: 0,
        assistantHeadcountTargetStage1: 0,
        assistantHeadcountTargetStage2: 0,
        majorProjectDepartmentTarget: 0
      },
      rules: {
        storeId: [
          { required: true, message: '请选择门店', trigger: 'change' }
        ],
        month: [
          { required: true, message: '请选择月份', trigger: 'change' }
        ]
      },
      businessUnitOptions: [],
      techDepartmentOptions: [],
      educationDepartmentOptions: [],
      majorProjectDepartmentOptions: [],
      managerList: []
    }
  },
  created() {

  },
  computed: {
    isEdit() {
      return this.formData && (this.formData.id || this.formData.Id)
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.initFormData()
          })
        }
      }
    }
  },
  methods: {
    // 获取事业部选项
    getBusinessUnitOptions() {
      lqmdtargetApi.previewDataInterface('734724946332222725').then(res => {
        this.businessUnitOptions = res.data.list || []
      }).catch(() => {
        this.businessUnitOptions = []
      })
      
    },
    // 获取科技部选项
    getTechDepartmentOptions() {
      lqmdtargetApi.previewDataInterface('734725044101448965').then(res => {
        this.techDepartmentOptions = res.data.list || []
      }).catch(() => {
        this.techDepartmentOptions = []
      })
    },
    // 获取教育部选项
    getEducationDepartmentOptions() {
      lqmdtargetApi.previewDataInterface('734725010941281541').then(res => {
        this.educationDepartmentOptions = res.data.list || []
      }).catch(() => {
        this.educationDepartmentOptions = []
      })
    },
    // 获取大项目部选项
    getMajorProjectDepartmentOptions() {
      lqmdtargetApi.previewDataInterface('734725079920805125').then(res => {
        this.majorProjectDepartmentOptions = res.data.list || []
      }).catch(() => {
        this.majorProjectDepartmentOptions = []
      })
    },
    // 获取总经理和经理列表
    async getManagerList() {
      try {
        const response = await lqmdtargetApi.getManagerList()
        this.managerList = response.data || []
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.managerList = []
      }
    },
    // 初始化表单数据
    initFormData() {
      this.getBusinessUnitOptions()
      this.getTechDepartmentOptions()
      this.getEducationDepartmentOptions()
      this.getMajorProjectDepartmentOptions()
      this.getManagerList()
      if (this.isEdit && this.formData) {
        // 编辑模式，填充现有数据
        this.localFormData = {
          storeId: this.formData.storeId || this.formData.StoreId || '',
          month: this.formData.month || this.formData.Month || '',
          businessUnit: this.formData.businessUnit || this.formData.BusinessUnit || '',
          techDepartment: this.formData.techDepartment || this.formData.TechDepartment || '',
          educationDepartment: this.formData.educationDepartment || this.formData.EducationDepartment || '',
          majorProjectDepartment: this.formData.majorProjectDepartment || this.formData.MajorProjectDepartment || '',
          businessUnitTarget: this.formData.businessUnitTarget !== undefined ? Number(this.formData.businessUnitTarget) : 0,
          techDepartmentTarget: this.formData.techDepartmentTarget !== undefined ? Number(this.formData.techDepartmentTarget) : 0,
          educationDepartmentTarget: this.formData.educationDepartmentTarget !== undefined ? Number(this.formData.educationDepartmentTarget) : 0,
          majorProjectDepartmentTarget: this.formData.majorProjectDepartmentTarget !== undefined ? Number(this.formData.majorProjectDepartmentTarget) : 0,
          businessUnitGeneralManager: this.formData.businessUnitGeneralManager || this.formData.BusinessUnitGeneralManager || '',
          businessUnitManager: this.formData.businessUnitManager || this.formData.BusinessUnitManager || '',
          storeTarget: this.formData.storeTarget !== undefined ? Number(this.formData.storeTarget) : 0,
          storeLifeline: this.formData.storeLifeline !== undefined ? Number(this.formData.storeLifeline) : 0,
          storeConsumeTarget: this.formData.storeConsumeTarget !== undefined ? Number(this.formData.storeConsumeTarget) : 0,
          storeProjectTarget: this.formData.storeProjectTarget !== undefined ? Number(this.formData.storeProjectTarget) : 0,
          storeHeadcountTarget: this.formData.storeHeadcountTarget !== undefined ? Number(this.formData.storeHeadcountTarget) : 0,
          assistantHeadcountTargetStage1: this.formData.assistantHeadcountTargetStage1 !== undefined ? Number(this.formData.assistantHeadcountTargetStage1) : 0,
          assistantHeadcountTargetStage2: this.formData.assistantHeadcountTargetStage2 !== undefined ? Number(this.formData.assistantHeadcountTargetStage2) : 0
        }
      } else {
        // 新增模式，重置表单
        this.localFormData = {
          storeId: '',
          month: '',
          businessUnit: '',
          techDepartment: '',
          educationDepartment: '',
          majorProjectDepartment: '',
          businessUnitTarget: 0,
          techDepartmentTarget: 0,
          educationDepartmentTarget: 0,
          majorProjectDepartmentTarget: 0,
          businessUnitGeneralManager: '',
          businessUnitManager: '',
          storeTarget: 0,
          storeLifeline: 0,
          storeConsumeTarget: 0,
          storeProjectTarget: 0,
          storeHeadcountTarget: 0,
          assistantHeadcountTargetStage1: 0,
          assistantHeadcountTargetStage2: 0
        }
      }
      
      // 清除验证状态
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate()
        }
      })
    },

    // 提交
    async handleSubmit() {
      if (!this.$refs.formRef) return
      
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) {
          return false
        }

        this.loading = true
        try {
          const submitData = {
            storeId: this.localFormData.storeId,
            month: this.localFormData.month,
            businessUnit: this.localFormData.businessUnit || '',
            techDepartment: this.localFormData.techDepartment || '',
            educationDepartment: this.localFormData.educationDepartment || '',
            majorProjectDepartment: this.localFormData.majorProjectDepartment || '',
            businessUnitTarget: Number(this.localFormData.businessUnitTarget) || 0,
            techDepartmentTarget: Number(this.localFormData.techDepartmentTarget) || 0,
            educationDepartmentTarget: Number(this.localFormData.educationDepartmentTarget) || 0,
            majorProjectDepartmentTarget: Number(this.localFormData.majorProjectDepartmentTarget) || 0,
            businessUnitGeneralManager: this.localFormData.businessUnitGeneralManager || '',
            businessUnitManager: this.localFormData.businessUnitManager || '',
            storeTarget: Number(this.localFormData.storeTarget) || 0,
            storeLifeline: Number(this.localFormData.storeLifeline) || 0,
            storeConsumeTarget: Number(this.localFormData.storeConsumeTarget) || 0,
            storeProjectTarget: Number(this.localFormData.storeProjectTarget) || 0,
            storeHeadcountTarget: Number(this.localFormData.storeHeadcountTarget) || 0,
            assistantHeadcountTargetStage1: Number(this.localFormData.assistantHeadcountTargetStage1) || 0,
            assistantHeadcountTargetStage2: Number(this.localFormData.assistantHeadcountTargetStage2) || 0
          }
          
          console.log('提交数据:', submitData)

          if (this.isEdit) {
            // 更新
            const id = this.formData.id || this.formData.Id
            await lqmdtargetApi.update(id, submitData)
            this.$message.success('更新成功')
          } else {
            // 新增
            await lqmdtargetApi.create(submitData)
            this.$message.success('新增成功')
          }
          
          this.$emit('success')
          this.handleClose()
        } catch (error) {
          console.error('提交失败:', error)
          this.$message.error(error.message || '提交失败')
        } finally {
          this.loading = false
        }
      })
    },

    // 处理可见性变化
    handleVisibleChange(val) {
      if (!val) {
        this.$emit('close')
      }
    },

    // 关闭弹窗
    handleClose() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-contentnew {
  max-height: 55vh;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 10px 0;
  box-sizing: border-box;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #E4E7ED;
}

::v-deep .el-divider__text {
  background-color: #fff;
  color: #409EFF;
  font-weight: 600;
}
</style>
