<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="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="开启共享">
        <el-switch v-model="shareEnabled" />
      </el-form-item>
      <el-form-item label="可见部门" v-if="shareEnabled">
        <el-select
          v-model="form.shareDeptIdList"
          multiple
          placeholder="请选择可见部门"
          style="width: 100%"
        >
          <el-option
            v-for="dept in deptOptions"
            :key="dept.deptId"
            :label="dept.deptName"
            :value="dept.deptId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建方式" prop="createMode">
        <el-radio-group v-model="form.createMode" :disabled="isEdit">
          <el-radio label="1">模板导入</el-radio>
          <el-radio label="2">绩效网格</el-radio>
          <el-radio label="3">地理网格</el-radio>
          <el-radio label="4">绘制网格</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 模板导入 -->
      <template v-if="form.createMode === '1'">
        <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>
      </template>

      <!-- 绩效网格 -->
      <template v-if="form.createMode === '2'">
        <el-form-item label="业务类型" prop="cmpmBizType">
          <el-select v-model="gridForm.cmpmBizType" placeholder="请选择业务类型" style="width: 100%" @change="handleCmpmBizTypeChange">
            <el-option label="零售" value="retail" />
            <el-option label="对公" value="corporate" />
            <el-option label="对公账户" value="corporate_account" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户经理" prop="userNames">
          <el-select
            v-model="gridForm.userNames"
            multiple
            filterable
            placeholder="请选择客户经理"
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.userName"
              :label="user.nickName"
              :value="user.userName"
            />
          </el-select>
        </el-form-item>
      </template>

      <!-- 地理网格 -->
      <template v-if="form.createMode === '3'">
        <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="gridForm.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.createMode === '4'">
        <el-form-item label="绘制网格" prop="drawGridIds">
          <el-select
            v-model="gridForm.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 {
  createCustGroupByGrid,
  createCustGroupByTemplate,
  updateCustGroupByGrid,
  updateCustGroupByTemplate,
  downloadTemplate,
  getManagerList,
  getRegionGridListForGroup
} from '@/api/group/custGroup'
import { getToken } from '@/utils/auth'
import { listUser } from '@/api/system/user'
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() },
      // 处理中提示
      processTipVisible: false
    }
  },
  computed: {
    // 是否正在处理中（创建或更新）
    isProcessing() {
      return this.form.createStatus === '0'
    },
    // 提交按钮文本
    submitButtonText() {
      if (this.submitting) return '提交中...'
      if (this.isEdit && this.isProcessing) return '客群处理中，请稍后...'
      return '确 定'
    }
  },
  data() {
    return {
      // 提交中状态
      submitting: false,
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + '/group/cust/createByTemplate',
      uploadHeaders: { Authorization: 'Bearer ' + getToken() },
      // 处理中提示
      processTipVisible: false,
      // 表单数据
      form: {
        id: null,
        groupName: null,
        groupMode: '0',
        createMode: '1',
        groupStatus: '0',
        shareEnabled: 0,
        shareDeptIdList: [],
        remark: null,
        validTime: null
      },
      // 共享开关
      shareEnabled: false,
      // 网格表单数据
      gridForm: {
        gridType: '0',
        cmpmBizType: null,
        userNames: [],
        regionGridIds: [],
        drawGridIds: []
      },
      // 上传文件
      uploadFile: null,
      // 表单验证规则
      rules: {
        groupName: [
          { required: true, message: '请输入客群名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        groupMode: [{ required: true, message: '请选择客群模式', trigger: 'change' }],
        createMode: [{ required: true, message: '请选择创建方式', trigger: 'change' }]
      },
      // 部门选项
      deptOptions: [],
      // 用户选项
      userOptions: [],
      // 地理网格选项
      regionGridOptions: [],
      // 地理网格查询条件
      regionQuery: {
        gridLevel: '1',
        gridDutyType: null,
        gridName: null
      },
      // 地理网格加载状态
      regionLoading: false,
      // 绘制网格选项
      drawGridOptions: []
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.init()
      }
    },
    groupData: {
      handler(val) {
        if (val && Object.keys(val).length > 0) {
          this.form = { ...val }
          this.shareEnabled = val.shareEnabled === 1
          // 解析 shareDeptIds 字符串为 shareDeptIdList 数组
          if (val.shareDeptIds) {
            this.form.shareDeptIdList = val.shareDeptIds.split(',').filter(id => id)
          } else {
            this.form.shareDeptIdList = []
          }

          // 反显网格数据（需要在 form.createMode watch 之后执行）
          this.$nextTick(() => {
            this.restoreGridData(val)
          })
        }
      },
      immediate: true
    },
    'form.createMode'(val) {
      // 重置网格表单
      this.gridForm = {
        gridType: val === '2' ? '0' : val === '3' ? '1' : '2',
        regionGridIds: [],
        drawGridIds: []
      }
      // 切换到地理网格模式时，重置查询条件
      if (val === '3') {
        this.resetRegionQuery()
      }
      // 切换到绘制网格模式时，加载绘制网格列表
      if (val === '4') {
        this.loadDrawGridOptions()
      }
    },
    'gridForm.cmpmBizType'(val) {
      // 当业务类型改变时，清空已选择的客户经理
      if (val) {
        this.gridForm.userNames = []
        this.loadManagerOptions()
      }
    },
    'form.createStatus'(val) {
      // 监听创建状态变化，显示提示
      if (this.isEdit && val === '0') {
        this.processTipVisible = true
      } else if (this.processTipVisible) {
        this.processTipVisible = false
      }
    }
  },
  created() {
    this.loadDeptOptions()
  },
  methods: {
    /** 初始化 */
    init() {
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
        // 编辑模式下，恢复网格数据
        if (this.isEdit && this.groupData && Object.keys(this.groupData).length > 0) {
          this.restoreGridData(this.groupData)
        }
      })
    },

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

      const createMode = String(data.createMode)
      // 根据创建方式反显网格数据
      if (createMode === '2' && data.gridType === '0') {
        // 绩效网格
        this.gridForm.gridType = '0'
        this.gridForm.cmpmBizType = data.cmpmBizType
        if (data.gridUserNames) {
          this.gridForm.userNames = data.gridUserNames.split(',').filter(n => n)
          // 加载客户经理选项
          this.loadManagerOptions()
        }
      } else if (createMode === '3' && data.gridType === '1') {
        // 地理网格 - 需要查询所有网格以便正确反显
        this.gridForm.gridType = '1'
        // 设置默认查询条件（获取所有网格）
        this.regionQuery = {
          gridLevel: '1',
          gridDutyType: null,
          gridName: null
        }
        if (data.regionGridIds) {
          this.gridForm.regionGridIds = data.regionGridIds.split(',').map(id => parseInt(id)).filter(id => id)
          // 加载地理网格选项（无查询条件，获取全部）
          this.loadRegionGridOptions()
        }
      } else if (createMode === '4' && data.gridType === '2') {
        // 绘制网格
        this.gridForm.gridType = '2'
        if (data.drawGridIds) {
          this.gridForm.drawGridIds = data.drawGridIds.split(',').map(id => parseInt(id)).filter(id => id)
          // 加载绘制网格选项
          this.loadDrawGridOptions()
        }
      }
    },

    /** 加载部门选项 */
    loadDeptOptions() {
      listDept().then(response => {
        this.deptOptions = response.data || []
      }).catch(() => {
        this.deptOptions = []
      })
    },

    /** 加载用户选项 */
    loadUserOptions() {
      listUser().then(response => {
        this.userOptions = response.rows || []
      }).catch(() => {
        this.userOptions = []
      })
    },

    /** 根据业务类型加载客户经理选项 */
    loadManagerOptions() {
      if (!this.gridForm.cmpmBizType) {
        this.userOptions = []
        return
      }
      getManagerList(this.gridForm.cmpmBizType).then(response => {
        this.userOptions = response.data || []
      }).catch(() => {
        this.userOptions = []
      })
    },

    /** 业务类型改变处理 */
    handleCmpmBizTypeChange(val) {
      // 清空已选择的客户经理
      this.gridForm.userNames = []
    },

    /** 加载地理网格选项 */
    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.gridForm.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) {
          // 处理共享设置
          this.form.shareEnabled = this.shareEnabled ? 1 : 0
          // 转换 shareDeptIdList 数组为 shareDeptIds 逗号分隔字符串
          this.form.shareDeptIds = this.form.shareDeptIdList.join(',')

          // 根据创建方式处理提交数据
          if (this.form.createMode === '1') {
            this.handleTemplateSubmit()
          } else {
            this.handleGridSubmit()
          }
        }
      })
    },

    /** 模板导入提交 */
    handleTemplateSubmit() {
      if (!this.uploadFile && !this.isEdit) {
        this.$modal.msgWarning('请选择要上传的文件')
        return
      }

      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.$modal.msgSuccess('客群更新中，请稍后刷新查看')
          this.submitting = false
          this.$emit('submit', { id: this.form.id })
          this.handleClose()
        }).catch(() => {
          this.submitting = false
        })
      } else {
        // 新增模式
        createCustGroupByTemplate(formData).then(response => {
          this.$modal.msgSuccess('客群创建中，请稍后刷新查看')
          this.submitting = false
          this.$emit('submit', { id: response.data })
          this.handleClose()
        }).catch(() => {
          this.submitting = false
        })
      }
    },

    /** 网格导入提交 */
    handleGridSubmit() {
      this.submitting = true

      // 构建提交数据
      const submitData = {
        custGroup: { ...this.form },
        gridType: this.form.createMode === '2' ? '0' : this.form.createMode === '3' ? '1' : '2',
        cmpmBizType: this.gridForm.cmpmBizType,
        userNames: this.gridForm.userNames,
        regionGridIds: this.gridForm.regionGridIds,
        drawGridIds: this.gridForm.drawGridIds
      }

      if (this.isEdit) {
        // 编辑模式：重新导入网格
        updateCustGroupByGrid(submitData).then(response => {
          // 使用后端返回的消息
          const msg = response.msg || '客群更新成功'
          if (msg.includes('更新中')) {
            this.$modal.msgSuccess('客群更新中，请稍后刷新查看')
          } else {
            this.$modal.msgSuccess(msg)
          }
          this.submitting = false
          this.$emit('submit', { id: this.form.id })
          this.handleClose()
        }).catch(() => {
          this.submitting = false
        })
      } else {
        // 新增模式
        createCustGroupByGrid(submitData).then(response => {
          this.$modal.msgSuccess('客群创建中，请稍后刷新查看')
          this.submitting = false
          this.$emit('submit', { id: response.data })
          this.handleClose()
        }).catch(() => {
          this.submitting = false
        })
      }
    },

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

    /** 重置表单 */
    resetForm() {
      this.form = {
        id: null,
        groupName: null,
        groupMode: '0',
        createMode: '1',
        groupStatus: '0',
        shareEnabled: 0,
        shareDeptIdList: [],
        remark: null,
        validTime: null
      }
      this.shareEnabled = false
      this.gridForm = {
        gridType: '0',
        cmpmBizType: null,
        userNames: [],
        regionGridIds: [],
        drawGridIds: []
      }
      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;
}
</style>
