<template>
  <div class="app-container">
    <!-- SOP信息卡片 -->
    <div style="margin-bottom: 10px">
      <el-card>
        <span class="custom-style" style="display: block; margin-bottom: 10px">SOP规则名称：{{ sopName }}</span>
        <span class="custom-style" style="display: block; margin-bottom: 10px">SOP规则编号：{{ queryParams.sopId }}</span>
        <span class="custom-style" style="display: block;">模板编号：{{ tempId }}</span>
      </el-card>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="执行账号" prop="accountId">
        <el-input
          v-model="queryParams.accountId"
          placeholder="请输入执行账号ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="营期时间" prop="startTime">
        <el-date-picker 
          clearable 
          size="small"
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择营期时间"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="正常" :value="0" />
          <el-option label="暂停" :value="1" />
        </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-tooltip class="item" effect="dark" content="删除营期后将不再给该营期发送消息，删除后不可恢复" placement="top">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['wx:sopUserLogsWx:remove']"
          >批量删除营期</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip class="item" effect="dark" content="修改选择的营期时间" placement="top">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleUpdateTime"
          >批量修改营期时间</el-button>
        </el-tooltip>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 提示信息 -->
    <div style="color: #999;font-size: 14px;display: flex;align-items: center;margin-bottom: 5px">
      <i class="el-icon-info"></i>
      【天数】：列表中的天数代表插件助手会发送任务模板里的第几天的消息
    </div>

    <!-- 营期数据表格 -->
    <el-table border v-loading="loading" :data="sopUserLogsWxList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="营期编号" align="center" prop="id" width="100" />
      <el-table-column label="SOP任务ID" align="center" prop="sopId" width="120" />
      <el-table-column label="执行账号ID" align="center" prop="accountId" width="150" />
      <el-table-column label="执行账号名称" align="center" prop="accountName" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.accountName">{{ scope.row.accountName }}</span>
          <span v-else style="color: #999;">未匹配</span>
        </template>
      </el-table-column>
      <el-table-column label="营期时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="天数" align="center" prop="countDays" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="warning">暂停</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wx:sopUserLogsWx:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 批量修改营期时间对话框 -->
    <el-dialog title="批量修改营期时间" :visible.sync="updateTimeOpen" width="500px" append-to-body>
      <el-form ref="updateTimeForm" :model="updateTimeForm" :rules="updateTimeRules" label-width="120px">
        <el-form-item label="选择营期时间" prop="newStartTime">
          <el-date-picker 
            clearable 
            size="small"
            v-model="updateTimeForm.newStartTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择新的营期时间"
            style="width: 100%;"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateTime">确 定</el-button>
        <el-button @click="updateTimeOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listSopUserLogsWx, 
  getSopUserLogsWx, 
  delSopUserLogsWx, 
  exportSopUserLogsWx,
  updateLogDate
} from "@/api/wx/sopUserLogsWx";

export default {
  name: "SopUserLogsScheduleWx",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 营期表格数据
      sopUserLogsWxList: [],
      // SOP名称
      sopName: '',
      // 模板ID
      tempId: '',
      // 批量修改营期时间对话框
      updateTimeOpen: false,
      // 批量修改营期时间表单
      updateTimeForm: {
        ids: [],
        newStartTime: null
      },
      // 批量修改营期时间表单校验
      updateTimeRules: {
        newStartTime: [
          { required: true, message: "请选择新的营期时间", trigger: "change" }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sopId: null,
        accountId: null,
        startTime: null,
        status: null
      }
    };
  },
  created() {
    // 从路由参数获取SOP ID
    const sopId = this.$route.params.id;
    if (sopId) {
      this.queryParams.sopId = sopId;
      this.sopName = this.$route.query.name || '';
      this.tempId = this.$route.query.tempId || '';
    }
    
    // 加载数据
    this.getList();
  },
  methods: {
    /** 查询营期列表 */
    getList() {
      this.loading = true;
      listSopUserLogsWx(this.queryParams).then(response => {
        console.log('个微SOP营期接口返回数据:', response);
        this.sopUserLogsWxList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('查询个微SOP营期失败:', error);
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    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;
    },
    /** 打开批量修改营期时间对话框 */
    handleUpdateTime() {
      this.updateTimeForm = {
        ids: this.ids,
        newStartTime: null
      };
      this.updateTimeOpen = true;
      this.$nextTick(() => {
        this.$refs["updateTimeForm"].clearValidate();
      });
    },
    /** 提交批量修改营期时间 */
    submitUpdateTime() {
      this.$refs["updateTimeForm"].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在修改中，请稍候...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          
          updateLogDate({
            ids: this.updateTimeForm.ids.join(','),
            newStartTime: this.updateTimeForm.newStartTime
          }).then(response => {
            console.log('批量修改个微SOP营期时间返回数据:', response);
            this.msgSuccess("修改成功");
            this.updateTimeOpen = false;
            this.getList();
          }).catch(error => {
            console.error('批量修改个微SOP营期时间失败:', error);
            this.msgError("修改失败");
          }).finally(() => {
            loading.close();
          });
        }
      });
    },
    /** 跳转到营期详情页面 */
    handleDetail(row) {
      this.$router.push({
        path: '/wxSop/sopUserLogsWx/detail',
        query: {
          sopUserId: row.id,
          sopId: row.sopId
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids.join(',');
      this.$confirm('删除营期后将不再给该营期发送消息，删除后不可恢复。是否确认删除营期编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delSopUserLogsWx(ids);
      }).then(response => {
        console.log('删除个微SOP营期返回数据:', response);
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(error => {
        if (error !== 'cancel') {
          console.error('删除个微SOP营期失败:', error);
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有个微SOP营期数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportSopUserLogsWx(this.queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
      });
    }
  }
};
</script>

<style scoped>
.custom-style {
  font-size: 14px;
  color: #606266;
}
</style>
