<template>
  <div class="app-container" style="padding: 0px !important;">
    <el-row :gutter="24" style="padding: 0 30px;">
        <el-col :span="6">
            <el-card class="stat-card stat-card-blue">
                <div class="stat-icon">
                    <i class="el-icon-bell"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-title">总预警推送次数</div>
                    <div class="stat-value">{{ cardInfo.alterCount }}</div>
                </div>
            </el-card>
        </el-col>
        <el-col :span="6">
            <el-card class="stat-card stat-card-blue2">
                <div class="stat-icon">
                    <i class="el-icon-data-analysis"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-title">反馈完成率</div>
                    <div class="stat-value">{{ cardInfo.completeRate + '%' }}</div>
                </div>
            </el-card>
        </el-col>
    </el-row>
    <el-form
      :model="searchArray"
      ref="searchArrayRef"
      size="small"
      :inline="true"
      style="margin-top:20px;"
    >
      <el-form-item label="日期">
        <el-date-picker
          v-model="reportTime"
          placeholder="请选择日期"
          @change="initCardList"
          style="width:100%"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="searchArray.status" placeholder="请选择状态" style="width: 100%" clearable>
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="预警类型" prop="alterType">
        <el-select
          v-model="searchArray.alterType"
          placeholder="请选择预警类型"
          clearable
          style="width:100%"
        >
          <el-option
            v-for="item in alterTypeOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="有无管户" prop="forwardFlag">
        <el-select
          v-model="searchArray.forwardFlag"
          placeholder="请选择"
          clearable
          style="width:100%"
        >
          <el-option
            v-for="item in forwardFlagOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchFn">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetFn">重置</el-button>
        <el-button
          v-if="canForwardByRole"
          type="warning"
          icon="el-icon-share"
          size="mini"
          :disabled="!canBatchForward"
          @click="openForwardDialog()"
        >批量转发</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <template>
        <el-table-column v-if="canForwardByRole" type="selection" width="55" :selectable="canSelectForwardRow" />
        <el-table-column label="序号" prop="xh" width="80">
          <template slot-scope="scope">
            <span>{{ scope.$index+1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户姓名" width="120" prop="custName" min-width="100" show-overflow-tooltip />
        <el-table-column label="客户号" width="230" prop="custId" min-width="140" show-overflow-tooltip />
        <el-table-column label="客户内码" width="200" prop="custIsn" min-width="140" show-overflow-tooltip />
        <el-table-column label="客户经理" width="200" prop="userInfo" min-width="140" show-overflow-tooltip />
        <el-table-column label="承接网点" width="180" prop="deptName" min-width="120" show-overflow-tooltip />
        <el-table-column label="预警类型" width="250" prop="alterType" min-width="100" show-overflow-tooltip />
        <el-table-column label="预警详情" prop="alterDetail" min-width="100" show-overflow-tooltip />
        <el-table-column label="是否已读" prop="isReed" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.isReed === '0'">否</span>
            <span v-else>是</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="250" prop="remark" min-width="100" show-overflow-tooltip />
        <el-table-column label="状态" width="150" prop="status" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.status | formatFilter('status',statusList) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="canForwardByRole" label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.canForward"
              size="mini"
              type="text"
              icon="el-icon-share"
              @click="openForwardDialog(scope.row)"
            >转发</el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="->,total,prev,pager,next,sizes"
      :total="total"
      :current-page="pageNum"
      @current-change="currentChangeFn"
      @size-change="sizeChangeFn"
    ></el-pagination>

    <el-dialog
      title="转发预警"
      :visible.sync="forwardVisible"
      width="520px"
      append-to-body
      v-if="forwardVisible"
    >
      <el-form ref="forwardFormRef" :model="forwardForm" :rules="forwardRules" label-width="100px">
        <el-form-item v-if="forwardMeta.historyOnly" label="转发方式">
          <span>按历史推荐转发</span>
        </el-form-item>
        <el-form-item v-if="isBranchAdmin" label="转发类型" prop="targetType">
          <template v-if="!forwardMeta.historyOnly">
          <el-radio-group v-model="forwardForm.targetType">
            <el-radio label="dept">转给网点</el-radio>
            <el-radio label="user">转给客户经理</el-radio>
          </el-radio-group>
          </template>
        </el-form-item>
        <el-form-item v-if="!forwardMeta.historyOnly && forwardForm.targetType === 'dept'" label="目标网点" prop="deptId">
          <el-select v-model="forwardForm.deptId" placeholder="请选择网点" style="width:100%">
            <el-option
              v-for="item in forwardMeta.deptOptions"
              :key="item.targetCode"
              :label="item.targetName"
              :value="Number(item.targetCode)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else-if="!forwardMeta.historyOnly" label="客户经理" prop="userName">
          <el-select
            v-model="forwardForm.userName"
            placeholder="请选择客户经理"
            filterable
            style="width:100%"
          >
            <el-option
              v-for="item in forwardMeta.userOptions"
              :key="item.targetCode"
              :label="item.targetName"
              :value="item.targetCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="forwardMeta.recommendedTargetCode && !isBatchForward && !forwardMeta.historyOnly"
          label="历史推荐"
        >
          <div class="recommend-row">
            <span>{{ recommendLabel }}</span>
            <el-button type="text" @click="applyRecommend">使用历史推荐</el-button>
          </div>
        </el-form-item>
        <el-form-item v-if="forwardMeta.historyOnly && isBatchForward" label="提示">
          <span>本次多选中包含有历史分配记录的客户，将按各自历史推荐自动转发；没有历史记录的预警将保留不动。</span>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" :loading="forwardSubmitting" @click="submitForward">确 定</el-button>
        <el-button @click="closeForwardDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  warningworkRecordList,
  warningCardNum,
  getAlterTypes,
  getAlterForwardMeta,
  forwardAlter
} from "@/api/system/home";
import _ from "lodash";
import dayjs from "dayjs";
import { mapGetters } from "vuex";
export default {
  name: "workmngdaytaskindex",
  computed: {
    ...mapGetters(["roles"]),
    isShowFlag() {
      let arr = _.intersection(this.roles, [
        "admin",
        "headAdmin",
        "branchAdmin",
        "headPublic",
        "headPrivate",
        "outletAdmin",
        "headOps"
      ]);
      if (arr.length > 0) {
        return true;
      } else {
        return false;
      }
    },
    isBranchAdmin() {
      return this.roles.includes("branchAdmin");
    },
    isOutletAdmin() {
      return this.roles.includes("outletAdmin");
    },
    canForwardByRole() {
      return this.isBranchAdmin || this.isOutletAdmin;
    },
    canBatchForward() {
      return this.selectedRows.length > 0 && this.selectedRows.every(item => item.canForward);
    },
    recommendLabel() {
      if (!this.forwardMeta.recommendedTargetCode) {
        return "";
      }
      return `${this.forwardMeta.recommendedTargetType === "dept" ? "网点" : "客户经理"}：${this.forwardMeta.recommendedTargetName}`;
    }
  },
  data() {
    return {
      reportTime: new Date(),
      cardInfo: {
          alterCount: '',
          completeRate: '',
      },
      statusList: [
        {
          label: "未完成",
          value: "0"
        },
        {
          label: "已完成",
          value: "2"
        }
      ],

      alterTypeOptions: [],
      forwardFlagOptions: [
        { label: "有管户", value: "0" },
        { label: "无管户", value: "1" }
      ],

      searchArray: {
        status: "",
        alterType: "",
        forwardFlag: ""
      },
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      selectedRows: [],
      total: 0,
      loading: false,
      forwardVisible: false,
      forwardSubmitting: false,
      isBatchForward: false,
      forwardMeta: {
        deptOptions: [],
        userOptions: [],
        recommendedTargetType: "",
        recommendedTargetCode: "",
        recommendedTargetName: "",
        historyOnly: false,
        hasHistoryRecommend: false
      },
      forwardForm: {
        ids: [],
        targetType: "user",
        deptId: "",
        userName: "",
        useHistory: false
      },
      forwardRules: {
        targetType: [{ required: true, message: "请选择转发类型", trigger: "change" }],
        deptId: [{ required: true, message: "请选择目标网点", trigger: "change" }],
        userName: [{ required: true, message: "请选择客户经理", trigger: "change" }]
      }
    };
  },
  created() {
    this.resetFn();
    this.initCardList();
    this.getAlterTypeList();
  },
  filters: {
    formatFilter(v, type, list) {
      if (type == "status") {
        let arr = _.filter(list, { value: v });
        return arr.length > 0 ? arr[0].label : '';
      }
    }
  },
  methods: {
    getAlterTypeList() {
      getAlterTypes().then(res => {
        if (res.code === 200) {
          this.alterTypeOptions = res.data || [];
        }
      });
    },
    initCardList() {
        warningCardNum({ reportTime: this.reportTime ? dayjs(this.reportTime).format('YYYY-MM-DD') + ' 23:59:59' : '' }).then(res => {
            this.cardInfo = res
        })
    },
    resetFn() {
      this.searchArray = {
        status: "",
        alterType: "",
        forwardFlag: ""
      };
      this.searchFn();
    },
    searchFn() {
      this.pageNum = 1;
      this.pageSize = 10;
      this.total = 0;
      this.queryListFn();
    },
    queryListFn() {
      this.loading = true;
      let p = {
        ...this.searchArray,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      warningworkRecordList(p).then(response => {
        this.loading = false;
        if (response.code == 200) {
          this.tableData = response.rows || [];
          this.selectedRows = [];
          this.total = response.total || 0;
        } else {
          this.$message.error(response.msg || "操作失败");
        }
      });
    },
    currentChangeFn(val) {
      this.pageNum = val;
      this.queryListFn();
    },
    sizeChangeFn(val) {
      this.pageSize = val;
      this.queryListFn();
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows || [];
    },
    canSelectForwardRow(row) {
      return !!row.canForward;
    },
    openForwardDialog(row) {
      const rows = row ? [row] : this.selectedRows.filter(item => item.canForward);
      if (!rows.length) {
        this.$message.warning("请先选择可转发的预警信息");
        return;
      }
      this.isBatchForward = rows.length > 1;
      this.forwardVisible = true;
      this.forwardSubmitting = false;
      this.forwardForm = {
        ids: rows.map(item => item.id),
        targetType: this.isBranchAdmin ? "dept" : "user",
        deptId: "",
        userName: "",
        useHistory: false
      };
      this.forwardMeta = {
        deptOptions: [],
        userOptions: [],
        recommendedTargetType: "",
        recommendedTargetCode: "",
        recommendedTargetName: "",
        historyOnly: false,
        hasHistoryRecommend: false
      };
      this.$nextTick(() => {
        this.$refs.forwardFormRef && this.$refs.forwardFormRef.clearValidate();
      });
      getAlterForwardMeta({ ids: rows.map(item => item.id).join(",") }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg || "获取转发信息失败");
          return;
        }
        this.forwardMeta = res.data || this.forwardMeta;
        this.forwardForm.useHistory = !!this.forwardMeta.historyOnly;
      });
    },
    applyRecommend() {
      if (!this.forwardMeta.recommendedTargetCode) {
        return;
      }
      if (this.forwardMeta.recommendedTargetType === "dept" && this.isOutletAdmin) {
        return;
      }
      this.forwardForm.targetType = this.forwardMeta.recommendedTargetType || this.forwardForm.targetType;
      if (this.forwardForm.targetType === "dept") {
        this.forwardForm.deptId = Number(this.forwardMeta.recommendedTargetCode);
        this.forwardForm.userName = "";
      } else {
        this.forwardForm.userName = this.forwardMeta.recommendedTargetCode;
        this.forwardForm.deptId = "";
      }
    },
    submitForward() {
      if (this.forwardMeta.historyOnly) {
        this.forwardForm.useHistory = true;
      }
      if (!this.forwardMeta.historyOnly && this.forwardForm.targetType === "dept" && !this.forwardForm.deptId) {
        this.$message.warning("请选择目标网点");
        return;
      }
      if (!this.forwardMeta.historyOnly && this.forwardForm.targetType === "user" && !this.forwardForm.userName) {
        this.$message.warning("请选择客户经理");
        return;
      }
      this.forwardSubmitting = true;
      forwardAlter(this.forwardForm).then(response => {
        this.forwardSubmitting = false;
        if (response.code == 200) {
          this.$message.success(response.msg || "转发完成");
          this.closeForwardDialog();
          this.queryListFn();
          this.initCardList();
        } else {
          this.$message.error(response.msg || "操作失败");
        }
      }).catch(() => {
        this.forwardSubmitting = false;
      })
    },
    closeForwardDialog() {
      this.forwardVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-pagination {
  margin-top: 15px;
}

// 统计卡片样式
.stat-card {
    height: 100px;
    border-radius: 8px;
    margin-top: 25px;
    border: none;
    display: flex;
    align-items: center;
    padding: 0 20px;
    position: relative;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    // 左侧装饰条
    &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background: rgba(255, 255, 255, 0.5);
    }

    .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(255, 255, 255, 0.2);
        margin-right: 12px;
        flex-shrink: 0;

        i {
            font-size: 22px;
            color: #fff;
        }
    }

    .stat-content {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 10px;

        .stat-title {
            font-size: 14px;
            color: rgba(255, 255, 255, 0.9);
            white-space: nowrap;
        }

        .stat-value {
            font-size: 20px;
            color: #fff;
            font-weight: bold;
        }
    }

    // 蓝色渐变卡片1（左上深→右下浅）
    &.stat-card-blue {
        background: linear-gradient(135deg, #1e7ee6 0%, #a0cfff 100%);
    }

    // 蓝色渐变卡片2（左上浅→右下深）
    &.stat-card-blue2 {
        background: linear-gradient(135deg, #a0cfff 0%, #1e7ee6 100%);
    }
}
.header-radio {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #ebebeb;

  .el-radio-button {
    flex: 1;

    ::v-deep .el-radio-button__inner {
      width: 100%;
      border: none;
      font-weight: 400;
      letter-spacing: 0.44px;
      line-height: 25px;
      font-size: 16px;
      color: #666666;
      padding: 11px 0 12px 0;
    }

    ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
      background-color: #4886f8;
      font-weight: 400;
      color: #ffffff;
      border-bottom-left-radius: 0;
      border-bottom-right-radius: 0;
    }

    &:nth-child(2) {
      &::before,
      &::after {
        content: "";
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        height: 21px;
        width: 1px;
        background: #ebebeb;
        z-index: 1;
      }

      &::after {
        right: 1px;
      }
    }

    &.is-active {
      &::before,
      &::after {
        content: none;
      }
    }
  }
}

.recommend-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}
</style>
