<template>
  <el-dialog
    :title="isEdit ? '编辑客群' : '创建客群'"
    :visible.sync="visible"
    width="700px"
    :before-close="handleClose"
    append-to-body
  >
    <el-alert
      v-if="isEdit && isProcessing"
      title="客群正在处理中，请等待处理完成后再进行编辑"
      type="warning"
      :closable="false"
      style="margin-bottom: 15px"
    />
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="submitting">
      <el-form-item label="客群名称" prop="groupName">
        <el-input v-model="form.groupName" placeholder="请输入客群名称" maxlength="50" />
      </el-form-item>
      <el-form-item label="客群模式" prop="groupMode">
        <el-radio-group v-model="form.groupMode" :disabled="isEdit && form.createStatus === '1'">
          <el-radio label="0">静态客群</el-radio>
          <el-radio label="1">动态客群</el-radio>
        </el-radio-group>
        <!-- <div class="form-tip">
          静态客群：创建后客户列表固定
          <br />
          动态客群：系统定期根据原始条件自动刷新客户列表
        </div> -->
      </el-form-item>
      <el-form-item label="客群类型" prop="groupType">
        <el-radio-group v-model="form.groupType" :disabled="isEdit">
          <el-radio label="0">零售类</el-radio>
          <el-radio label="1">公司类</el-radio>
        </el-radio-group>
        <!-- <div class="form-tip">
          零售类：只能导入个人和商户客户
          <br />
          公司类：只能导入企业客户
        </div> -->
      </el-form-item>
      <el-form-item label="有效期" prop="validTime">
        <el-date-picker
          v-model="form.validTime"
          type="datetime"
          placeholder="选择有效期截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%"
        />
        <div class="form-tip">留空表示永久有效</div>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="2" />
      </el-form-item>

      <el-form-item label="客群标签">
        <div class="tag-input-wrapper">
          <el-input
            v-model="tagInput"
            placeholder="输入标签后点击加号添加"
            style="width: calc(100% - 40px)"
            @keyup.enter.native="addTag"
          />
          <el-button type="primary" icon="el-icon-plus" @click="addTag" style="margin-left: 8px" />
        </div>
        <div class="tag-list" v-if="allTags.length > 0">
          <span class="tag-label">已有标签：</span>
          <el-tag
            v-for="tag in allTags"
            :key="tag"
            :type="selectedTags.includes(tag) ? 'primary' : 'info'"
            :effect="selectedTags.includes(tag) ? 'dark' : 'plain'"
            @click="toggleTag(tag)"
            style="cursor: pointer; margin-right: 8px; margin-bottom: 8px"
          >
            {{ tag }}
          </el-tag>
        </div>
        <div class="selected-tags" v-if="selectedTags.length > 0">
          <span class="tag-label">已选标签：</span>
          <el-tag
            v-for="tag in selectedTags"
            :key="tag"
            closable
            @close="removeTag(tag)"
            style="margin-right: 8px; margin-bottom: 8px"
          >
            {{ tag }}
          </el-tag>
        </div>
      </el-form-item>

      <el-form-item label="开启共享">
        <el-switch v-model="shareEnabled" />
      </el-form-item>
      <el-form-item label="可见部门" v-if="shareEnabled">
        <el-select
          v-model="shareDeptList"
          multiple
          filterable
          placeholder="请选择可见部门"
          style="width: 100%"
          popper-class="dept-select-popper"
        >
          <el-option
            v-for="dept in deptOptions"
            :key="dept.deptId"
            :label="dept.deptName"
            :value="String(dept.deptId)"
          />
        </el-select>
      </el-form-item>

      <!-- 模板导入 -->
      <el-form-item label="客户文件" prop="file">
        <el-upload
          ref="upload"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-change="handleFileChange"
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-button slot="trigger" size="small" icon="el-icon-upload">选择文件</el-button>
          <el-button size="small" type="text" @click.stop="downloadTemplate" style="margin-left: 15px">
            下载模板
          </el-button>
          <div slot="tip" class="el-upload__tip">
            仅支持Excel文件，文件大小不超过10MB
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="匹配网格类型" prop="gridType">
        <el-radio-group v-model="form.gridType" @change="handleGridTypeChange">
          <el-radio label="0">绩效网格</el-radio>
          <!-- 暂时隐藏，后续版本开放
          <el-radio label="1">地理网格</el-radio>
          <el-radio label="2">绘制网格</el-radio>
          -->
        </el-radio-group>
        <div class="form-tip">
          系统将根据客户信息从所选网格匹配管户关系，匹配不上则保存空的管户关系
        </div>
      </el-form-item>

      <!-- 地理网格筛选 - 暂时隐藏，后续版本开放
      <template v-if="form.gridType === '1'">
        <el-form-item label="网格级别">
          <el-radio-group v-model="regionQuery.gridLevel">
            <el-radio label="1">总行行政网格</el-radio>
            <el-radio label="2">支行行政网格</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="责任类型">
          <el-select v-model="regionQuery.gridDutyType" placeholder="请选择责任类型" style="width: 100%" clearable>
            <el-option label="责任网格" value="1" />
            <el-option label="竞争网格" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="网格名称">
          <el-input v-model="regionQuery.gridName" placeholder="请输入网格名称（可选）" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="loadRegionGridOptions" :loading="regionLoading">查询网格</el-button>
          <el-button icon="el-icon-refresh" @click="resetRegionQuery">重置条件</el-button>
        </el-form-item>
        <el-form-item label="选择网格">
          <el-select
            v-model="form.regionGridIds"
            multiple
            filterable
            collapse-tags
            placeholder="请选择网格"
            style="width: 100%"
          >
            <el-option
              v-for="grid in regionGridOptions"
              :key="grid.gridId"
              :label="grid.gridName"
              :value="grid.gridId"
            />
          </el-select>
        </el-form-item>
      </template>
      -->

      <!-- 绘制网格筛选 - 暂时隐藏，后续版本开放
      <template v-if="form.gridType === '2'">
        <el-form-item label="绘制网格">
          <el-select
            v-model="form.drawGridIds"
            multiple
            filterable
            placeholder="请选择网格"
            style="width: 100%"
          >
            <el-option
              v-for="grid in drawGridOptions"
              :key="grid.gridId"
              :label="grid.gridName"
              :value="grid.gridId"
            />
          </el-select>
        </el-form-item>
      </template>
      -->
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" :loading="submitting" :disabled="isProcessing" @click="handleSubmit">
        {{ submitButtonText }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  createCustGroupByTemplate,
  updateCustGroupByTemplate,
  downloadTemplate,
  getRegionGridListForGroup,
  getCreateStatus,
  getAllGroupTags
} from '@/api/group/custGroup'
import { getToken } from '@/utils/auth'
import { listDept } from '@/api/system/dept'
import { getSimpleGridList } from '@/api/grid/list/gridlist'

export default {
  name: 'CreateDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    groupData: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 提交中状态
      submitting: false,
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + '/group/cust/createByTemplate',
      uploadHeaders: { Authorization: 'Bearer ' + getToken() },
      // 表单数据
      form: {
        id: null,
        groupName: null,
        groupMode: '0',
        groupType: '0',
        groupStatus: '0',
        gridType: '0',
        regionGridIds: [],
        drawGridIds: [],
        shareEnabled: 0,
        shareDeptIdList: [],
        remark: null,
        validTime: null
      },
      // 共享开关
      shareEnabled: false,
      // 已选部门列表（字符串数组，用于el-select绑定）
      shareDeptList: [],
      // 上传文件
      uploadFile: null,
      // 表单验证规则
      rules: {
        groupName: [
          { required: true, message: '请输入客群名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        groupMode: [{ required: true, message: '请选择客群模式', trigger: 'change' }],
        groupType: [{ required: true, message: '请选择客群类型', trigger: 'change' }],
        gridType: [{ required: true, message: '请选择匹配网格类型', trigger: 'change' }]
      },
      // 部门选项
      deptOptions: [],
      // 地理网格选项
      regionGridOptions: [],
      // 地理网格查询条件
      regionQuery: {
        gridLevel: '1',
        gridDutyType: null,
        gridName: null
      },
      // 地理网格加载状态
      regionLoading: false,
      // 绘制网格选项
      drawGridOptions: [],
      // 轮询定时器
      pollTimer: null,
      // 标签输入框内容
      tagInput: '',
      // 所有已有标签列表
      allTags: [],
      // 已选标签列表
      selectedTags: [],
      // 关闭弹窗时是否保留状态轮询
      keepPollingOnClose: false
    }
  },
  computed: {
    // 是否正在处理中（创建或更新）
    isProcessing() {
      return this.form.createStatus === '0'
    },
    // 提交按钮文本
    submitButtonText() {
      if (this.submitting) return '提交中...'
      if (this.isEdit && this.isProcessing) return '客群处理中，请稍后...'
      return '确 定'
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.init()
        if (this.shareEnabled && this.deptOptions.length === 0) {
          this.loadDeptOptions()
        }
      }
    },
    shareEnabled(val) {
      if (val && this.deptOptions.length === 0) {
        this.loadDeptOptions()
      }
    },
    groupData: {
      handler(val) {
        if (val && Object.keys(val).length > 0) {
          this.form = { ...val }
          this.shareEnabled = val.shareEnabled === 1
          // 解析 shareDeptIds 字符串为 shareDeptList 数组（保持字符串类型以匹配el-option的value）
          if (val.shareDeptIds) {
            this.shareDeptList = val.shareDeptIds.split(',').filter(id => id)
          } else {
            this.shareDeptList = []
          }
          // 解析网格ID
          if (val.regionGridIds) {
            this.form.regionGridIds = val.regionGridIds.split(',').map(id => parseInt(id)).filter(id => id)
          } else {
            this.form.regionGridIds = []
          }
          if (val.drawGridIds) {
            this.form.drawGridIds = val.drawGridIds.split(',').map(id => parseInt(id)).filter(id => id)
          } else {
            this.form.drawGridIds = []
          }
          // 解析标签
          if (val.groupTags) {
            this.selectedTags = val.groupTags.split(',').map(tag => tag.trim()).filter(tag => tag)
          } else {
            this.selectedTags = []
          }

          // 反显网格数据
          this.$nextTick(() => {
            this.restoreGridData(val)
          })
        }
      },
      immediate: true
    }
  },
  created() {
    this.loadAllTags()
  },
  beforeDestroy() {
    this.clearPollTimer()
  },
  methods: {
    /** 初始化 */
    init() {
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },

    /** 反显网格数据 */
    restoreGridData(data) {
      if (!this.isEdit || !data.gridType) return

      if (data.gridType === '1') {
        this.resetRegionQuery()
        if (data.regionGridIds) {
          this.loadRegionGridOptions()
        }
      } else if (data.gridType === '2') {
        this.loadDrawGridOptions()
      }
    },

    /** 加载部门选项 */
    loadDeptOptions() {
      listDept().then(response => {
        // 将树形结构扁平化，以便el-select遍历
        this.deptOptions = this.flattenDeptList(response.data || [])
      }).catch(() => {
        this.deptOptions = []
      })
    },

    /** 扁平化部门树 */
    flattenDeptList(list, result = []) {
      list.forEach(item => {
        result.push({ deptId: item.deptId, deptName: item.deptName })
        if (item.children && item.children.length > 0) {
          this.flattenDeptList(item.children, result)
        }
      })
      return result
    },

    /** 加载所有已有标签 */
    loadAllTags() {
      getAllGroupTags().then(response => {
        this.allTags = response.data || []
      }).catch(() => {
        this.allTags = []
      })
    },

    /** 添加标签 */
    addTag() {
      const tag = this.tagInput.trim()
      if (!tag) return
      if (this.selectedTags.includes(tag)) {
        this.$message.warning('该标签已添加')
        return
      }
      this.selectedTags.push(tag)
      // 如果是新标签，添加到allTags中
      if (!this.allTags.includes(tag)) {
        this.allTags.push(tag)
      }
      this.tagInput = ''
    },

    /** 切换标签选中状态 */
    toggleTag(tag) {
      const index = this.selectedTags.indexOf(tag)
      if (index > -1) {
        this.selectedTags.splice(index, 1)
      } else {
        this.selectedTags.push(tag)
      }
    },

    /** 移除已选标签 */
    removeTag(tag) {
      const index = this.selectedTags.indexOf(tag)
      if (index > -1) {
        this.selectedTags.splice(index, 1)
      }
    },

    /** 网格类型改变处理 */
    handleGridTypeChange(val) {
      if (val === '1') {
        this.resetRegionQuery()
      } else if (val === '2') {
        this.loadDrawGridOptions()
      }
      // 清空网格选择
      this.form.regionGridIds = []
      this.form.drawGridIds = []
    },

    /** 加载地理网格选项 */
    loadRegionGridOptions() {
      this.regionLoading = true
      const params = {
        gridLevel: this.regionQuery.gridLevel
      }
      if (this.regionQuery.gridDutyType) {
        params.gridDutyType = this.regionQuery.gridDutyType
      }
      if (this.regionQuery.gridName) {
        params.gridName = this.regionQuery.gridName
      }

      getRegionGridListForGroup(params).then(response => {
        this.regionGridOptions = response.data || []
      }).catch(() => {
        this.regionGridOptions = []
      }).finally(() => {
        this.regionLoading = false
      })
    },

    /** 重置地理网格查询条件 */
    resetRegionQuery() {
      this.regionQuery = {
        gridLevel: '1',
        gridDutyType: null,
        gridName: null
      }
      this.form.regionGridIds = []
    },

    /** 加载绘制网格选项 */
    loadDrawGridOptions() {
      getSimpleGridList().then(response => {
        this.drawGridOptions = response.data || []
      }).catch(() => {
        this.drawGridOptions = []
      })
    },

    /** 文件改变 */
    handleFileChange(file) {
      this.uploadFile = file.raw
    },

    /** 上传成功 */
    handleUploadSuccess(response) {
      this.$modal.msgSuccess('创建成功')
      this.submitting = false
      this.$emit('submit', { id: response.data })
      this.handleClose()
    },

    /** 上传失败 */
    handleUploadError() {
      this.$modal.msgError('创建失败')
      this.submitting = false
    },

    /** 下载模板 */
    downloadTemplate() {
      downloadTemplate().then(response => {
        const url = window.URL.createObjectURL(new Blob([response]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '客户信息模板.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    },

    /** 提交表单 */
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.uploadFile && !this.isEdit) {
            this.$modal.msgWarning('请选择要上传的文件')
            return
          }

          // 处理共享设置
          this.form.shareEnabled = this.shareEnabled ? 1 : 0
          // 转换 shareDeptIdList 数组为 shareDeptIds 逗号分隔字符串
          this.form.shareDeptIds = this.shareDeptList.join(',')
          // 转换选中的标签为逗号分隔字符串
          this.form.groupTags = this.selectedTags.join(',')
          // 转换网格ID数组为逗号分隔字符串
          this.form.regionGridIds = this.form.regionGridIds.join(',')
          this.form.drawGridIds = this.form.drawGridIds.join(',')

          this.submitting = true

          // 构建表单数据
          const formData = new FormData()
          formData.append('dto', JSON.stringify(this.form))
          if (this.uploadFile) {
            formData.append('file', this.uploadFile)
          }

          if (this.isEdit) {
            // 编辑模式
            updateCustGroupByTemplate(formData).then(response => {
              this.submitting = false
              if (response.msg === '客群更新成功') {
                // 没有上传文件，直接更新成功
                this.$modal.msgSuccess('客群更新成功')
                this.$emit('submit', { id: this.form.id, refresh: true })
              } else {
                // 有上传文件，后台正在处理
                this.$modal.msgSuccess('客群更新任务已提交，后台正在处理')
                this.keepPollingOnClose = true
                this.startPollingStatus(this.form.id)
              }
              this.handleClose()
            }).catch(() => {
              this.submitting = false
            })
          } else {
            // 新增模式
            createCustGroupByTemplate(formData).then(response => {
              const groupId = response && response.data ? response.data : null
              if (!groupId) {
                this.$modal.msgError('客群创建成功但未获取到任务ID，请稍后在列表中查看状态')
                this.submitting = false
                this.handleClose()
                return
              }
              this.$modal.msgSuccess('客群创建任务已提交，后台正在处理')
              this.submitting = false
              this.keepPollingOnClose = true
              this.startPollingStatus(groupId)
              this.handleClose()
            }).catch(() => {
              this.submitting = false
            })
          }
        }
      })
    },

    /** 关闭弹窗 */
    handleClose() {
      this.$emit('update:visible', false)
      this.resetForm()
    },

    /** 开始轮询创建状态 */
    startPollingStatus(groupId) {
      if (!groupId || groupId === 'undefined' || groupId === 'null') {
        return
      }
      this.clearPollTimer()
      // 每30秒轮询一次
      this.pollTimer = setInterval(() => {
        getCreateStatus(groupId).then(res => {
          const status = res.data
          if (status === '1') {
            // 创建成功
            this.clearPollTimer()
            this.keepPollingOnClose = false
            window.dispatchEvent(new Event('notice-center-refresh'))
            this.$modal.msgSuccess('客群导入完成')
            this.$emit('submit', { id: groupId, refresh: true })
          } else if (status === '2') {
            // 创建失败
            this.clearPollTimer()
            this.keepPollingOnClose = false
            window.dispatchEvent(new Event('notice-center-refresh'))
            this.$modal.msgError('客群导入失败，请查看消息中心了解详情')
          }
        }).catch(() => {
          // 查询失败，继续轮询
        })
      }, 30000)
    },

    /** 清除轮询定时器 */
    clearPollTimer() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer)
        this.pollTimer = null
      }
    },

    /** 重置表单 */
    resetForm() {
      if (!this.keepPollingOnClose) {
        this.clearPollTimer()
      }
      this.form = {
        id: null,
        groupName: null,
        groupMode: '0',
        groupType: '0',
        groupStatus: '0',
        gridType: '0',
        regionGridIds: [],
        drawGridIds: [],
        shareEnabled: 0,
        shareDeptIdList: [],
        remark: null,
        validTime: null
      }
      this.shareEnabled = false
      this.shareDeptList = []
      this.tagInput = ''
      this.selectedTags = []
      this.uploadFile = null
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    }
  }
}
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 5px;
}

.tag-input-wrapper {
  display: flex;
  align-items: center;
}

.tag-list,
.selected-tags {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.tag-label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}
</style>

<style>
/* 解决弹窗内下拉框被遮挡的问题 */
.dept-select-popper {
  z-index: 9999 !important;
}
</style>
