<template>
  <div class="app-container push-config-page">
    <el-alert
      type="info"
      :closable="false"
      show-icon
      class="tip-banner"
      title="① 已转入未转出 / 开工未转入：工段矩阵 → 各工段长收单 Sheet；「汇总接收人」→ 收全工段多 Sheet Excel（留空则发给矩阵里所有人）。② 汇报未质检 / 质检未入库：填钉钉用户ID。③ 其他：填用户ID私发，留空发群。"
    />

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="推送名称" prop="pushName">
        <el-input v-model="queryParams.pushName" placeholder="推送名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-select v-model="queryParams.enabled" placeholder="全部" clearable style="width: 120px">
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:workAlertPushConfig:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:workAlertPushConfig:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:workAlertPushConfig:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <div class="table-wrap">
      <el-table
        ref="configTable"
        v-loading="loading"
        :data="configList"
        row-key="id"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="48" align="center" fixed="left" />
        <el-table-column label="推送名称" prop="pushName" min-width="130" show-overflow-tooltip fixed="left" />
        <el-table-column label="任务编码" prop="pushCode" min-width="200" show-overflow-tooltip />
        <el-table-column label="推送时间" prop="pushTime" width="88" align="center" />
        <el-table-column label="启用" prop="enabled" width="72" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="row.enabled === '1' ? 'success' : 'info'" size="mini">{{ row.enabled === '1' ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="私发/汇总" prop="dingUserIds" min-width="120" show-overflow-tooltip />
        <el-table-column label="分对象" prop="recipientRules" min-width="100" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span v-if="row.recipientRules">{{ formatRecipientSummary(row.recipientRules) }}</span>
            <span v-else class="text-muted">—</span>
          </template>
        </el-table-column>
        <el-table-column label="上次推送" prop="lastPushDate" width="108" align="center">
          <template slot-scope="{ row }">{{ row.lastPushDate || '—' }}</template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="220" align="center" class-name="action-col">
          <template slot-scope="{ row }">
            <div class="action-cell">
              <el-button size="mini" type="text" icon="el-icon-video-play" @click="handleTrigger(row)" v-hasPermi="['system:workAlertPushConfig:trigger']">立即推送</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)" v-hasPermi="['system:workAlertPushConfig:edit']">编辑</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(row)" v-hasPermi="['system:workAlertPushConfig:remove']">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="推送任务" prop="pushCode">
          <el-select v-model="form.pushCode" placeholder="选择推送任务" filterable style="width: 100%" :disabled="!!form.id" @change="onPushCodeChange">
            <el-option v-for="item in pushTypeOptions" :key="item.code" :label="item.name + ' (' + item.code + ')'" :value="item.code">
              <span>{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px">{{ item.code }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推送名称" prop="pushName">
          <el-input v-model="form.pushName" placeholder="显示名称" />
        </el-form-item>
        <el-form-item label="每日推送时间" prop="pushTime">
          <el-time-select
            v-model="form.pushTime"
            :picker-options="{ start: '06:00', step: '00:05', end: '22:00' }"
            placeholder="选择时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item v-if="isPerWorkCenterMode" label="工段接收人">
          <div class="wc-recipient-block">
            <p class="wc-tip">各工段长 StaffId（逗号分隔）。有数据且已填写的工段才会收到本工段单 Sheet Excel。</p>
            <el-table :data="workCenterRows" border size="mini" max-height="280">
              <el-table-column label="工段" prop="name" width="100" />
              <el-table-column label="StaffId">
                <template slot-scope="{ row }">
                  <el-input v-model="row.userIds" size="mini" placeholder="工段长 StaffId" />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item v-if="isPerWorkCenterMode" label="汇总接收人">
          <el-input
            v-model="form.dingUserIds"
            type="textarea"
            :rows="2"
            placeholder="收全工段多 Sheet 汇总 Excel 的人员 StaffId（如生产主管）；留空则发给工段矩阵里全部人员"
          />
        </el-form-item>
        <el-form-item v-else label="钉钉用户ID" prop="dingUserIds">
          <el-input
            v-model="form.dingUserIds"
            type="textarea"
            :rows="3"
            :placeholder="roleRecipientPlaceholder"
          />
        </el-form-item>
        <el-form-item label="群会话ID">
          <el-input v-model="form.openConversationId" placeholder="仅群发模式需要；私发模式可留空" />
        </el-form-item>
        <el-form-item label="机器人Code">
          <el-input v-model="form.robotCode" placeholder="留空使用 dingtalk.robot-code（需与机器人应用一致）" />
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-radio-group v-model="form.enabled">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sortOrder" :min="0" :max="9999" controls-position="right" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="备注说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWorkAlertPushConfig,
  getWorkAlertPushConfig,
  addWorkAlertPushConfig,
  updateWorkAlertPushConfig,
  delWorkAlertPushConfig,
  listPushTypes,
  triggerWorkAlertPush
} from '@/api/system/workAlertPushConfig'

const WORK_CENTERS = [
  '机一工段', '机二工段', '焊接工段', '装一工段', '装二工段', '机加委外', '电钳工段', '下料工段'
]

const PER_WORK_CENTER_CODES = ['getMassageTransInPendingOut', 'getMassageStartedNotTransIn']

export default {
  name: 'WorkAlertPushConfig',
  data() {
    return {
      loading: true,
      buttonLoading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      configList: [],
      pushTypeOptions: [],
      title: '',
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pushName: undefined,
        enabled: undefined
      },
      form: {},
      workCenterRows: [],
      rules: {
        pushCode: [{ required: true, message: '请选择推送任务', trigger: 'change' }],
        pushName: [{ required: true, message: '推送名称不能为空', trigger: 'blur' }],
        pushTime: [{ required: true, message: '请选择推送时间', trigger: 'change' }],
        enabled: [{ required: true, message: '请选择启用状态', trigger: 'change' }]
      }
    }
  },
  computed: {
    isPerWorkCenterMode() {
      return PER_WORK_CENTER_CODES.includes(this.form.pushCode)
    },
    roleRecipientPlaceholder() {
      if (this.form.pushCode === 'getProcessReportNotInspected') {
        return '质检人员 StaffId，多个英文逗号分隔（私发单 Sheet「汇报未质检」）'
      }
      if (this.form.pushCode === 'getProcessReportNotStockedIn') {
        return '库房人员 StaffId，多个英文逗号分隔（私发单 Sheet「质检未入库」）'
      }
      return '私发接收人 StaffId，多个英文逗号分隔；留空则发默认群'
    }
  },
  created() {
    this.loadPushTypes()
    this.getList()
  },
  methods: {
    loadPushTypes() {
      listPushTypes().then(res => {
        this.pushTypeOptions = res.data || []
      })
    },
    getList() {
      this.loading = true
      listWorkAlertPushConfig(this.queryParams).then(response => {
        this.configList = response.rows
        this.total = response.total
        this.loading = false
        this.layoutTable()
      })
    },
    layoutTable() {
      this.$nextTick(() => {
        const table = this.$refs.configTable
        if (table && table.doLayout) {
          table.doLayout()
        }
      })
    },
    onPushCodeChange(code) {
      const item = this.pushTypeOptions.find(p => p.code === code)
      if (item && !this.form.pushName) {
        this.form.pushName = item.name
        this.form.remark = item.remark
      }
      if (PER_WORK_CENTER_CODES.includes(code)) {
        this.initWorkCenterRows(this.form.recipientRules)
      }
    },
    initWorkCenterRows(recipientRulesJson) {
      this.workCenterRows = WORK_CENTERS.map(name => ({ name, userIds: '' }))
      if (!recipientRulesJson) return
      try {
        const obj = JSON.parse(recipientRulesJson)
        this.workCenterRows.forEach(row => {
          if (obj[row.name]) {
            row.userIds = obj[row.name]
          }
        })
      } catch (e) {
        /* ignore invalid json */
      }
    },
    buildRecipientRulesJson() {
      if (!this.isPerWorkCenterMode) return undefined
      const obj = {}
      this.workCenterRows.forEach(row => {
        if (row.userIds && row.userIds.trim()) {
          obj[row.name] = row.userIds.trim()
        }
      })
      return Object.keys(obj).length ? JSON.stringify(obj) : undefined
    },
    formatRecipientSummary(json) {
      try {
        const obj = JSON.parse(json)
        const keys = Object.keys(obj)
        return keys.length ? keys.length + ' 个工段' : '—'
      } catch (e) {
        return '已配置'
      }
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: undefined,
        pushCode: undefined,
        pushName: undefined,
        pushTime: '08:30',
        dingUserIds: undefined,
        recipientRules: undefined,
        openConversationId: undefined,
        robotCode: undefined,
        enabled: '0',
        sortOrder: 0,
        remark: undefined
      }
      this.workCenterRows = []
      this.resetForm('form')
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增预警推送配置'
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getWorkAlertPushConfig(id).then(response => {
        this.form = response.data
        this.initWorkCenterRows(this.form.recipientRules)
        this.open = true
        this.title = '修改预警推送配置'
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.buttonLoading = true
        const payload = { ...this.form }
        if (this.isPerWorkCenterMode) {
          payload.recipientRules = this.buildRecipientRulesJson()
        } else {
          payload.recipientRules = undefined
        }
        const req = payload.id ? updateWorkAlertPushConfig(payload) : addWorkAlertPushConfig(payload)
        req.then(() => {
          this.$modal.msgSuccess(this.form.id ? '修改成功' : '新增成功')
          this.open = false
          this.getList()
        }).finally(() => {
          this.buttonLoading = false
        })
      })
    },
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids
      this.$modal.confirm('是否确认删除选中的配置？').then(() => {
        return delWorkAlertPushConfig(ids.join(','))
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleTrigger(row) {
      this.$modal.confirm('确认立即执行「' + row.pushName + '」推送？').then(() => {
        return triggerWorkAlertPush(row.id)
      }).then(() => {
        this.$modal.msgSuccess('推送任务已触发')
        this.getList()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.push-config-page .tip-banner {
  margin-bottom: 16px;
}

.wc-recipient-block .wc-tip {
  margin: 0 0 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

.text-muted {
  color: #c0c4cc;
}

.table-wrap {
  width: 100%;
  overflow-x: auto;
}

.action-cell {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  gap: 2px 4px;
  min-height: 28px;
}

.push-config-page ::v-deep .action-col .cell {
  overflow: visible;
  white-space: normal;
}
</style>
