<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择推送类型" clearable size="small">
          <el-option
            v-for="dict in pushCountTypeList"
            :key="dict.dictSort"
            :label="dict.dictLabel"
            :value="dict.dictSort"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="限定次数" prop="pushCount">
        <el-input
          v-model="queryParams.pushCount"
          placeholder="请输入限定次数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="推送公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          placeholder="请选择推送公司"
          clearable
          filterable
          size="small"
          @change="handleQuery"
        >
          <!-- 公司选项 -->
          <el-option
            v-for="company in companys"
            :key="company.companyId"
            :label="company.companyName"
            :value="company.companyId"
          />
        </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="['qw:qwPushCount:add']"
        >新增
        </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="['qw:qwPushCount:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['qw:qwPushCount:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="qwPushCountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="pushCountTypeList" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="推送公司" align="center" prop="companyId">
        <template slot-scope="scope">
          <span>{{ getCompanyNameById(scope.row.companyId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="限定次数" align="center" prop="pushCount"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qw:qwPushCount:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qw:qwPushCount: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="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="推送类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择推送类型" clearable size="small">
            <el-option
              v-for="dict in pushCountTypeList"
              :key="dict.dictSort"
              :label="dict.dictLabel"
              :value="dict.dictSort"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="限定次数" prop="pushCount">
          <el-input-number v-model="form.pushCount" placeholder="限定次数"/>
        </el-form-item>

        <el-form-item label="销售公司" prop="companyId">
          <el-select v-model="form.companyIdList"
                     placeholder="请选择推送公司"
                     multiple
                     size="small">
            <!-- 公司选项 -->
            <el-option
              v-for="company in companys"
              :key="company.companyId"
              :label="company.companyName"
              :value="company.companyId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改企业消息的次数对话框 -->
    <el-dialog :title="title" :visible.sync="openSingle" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="推送类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择推送类型"
            clearable
            size="small"
            value-key="dictValue"
          >
            <el-option
              v-for="dict in pushCountTypeList"
              :key="dict.dictSort"
              :label="dict.dictLabel"
              :value="dict.dictSort"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="限定次数" prop="pushCount">
          <el-input v-model="form.pushCount" placeholder="限定次数"/>
        </el-form-item>

        <el-form-item label="推送公司" prop="companyId">
          <el-select
            v-model="form.companyId"
            placeholder="请选择推送公司"
            clearable
            filterable
            collapse-tags
            size="small">
            <!-- 公司选项 -->
            <el-option
              v-for="company in companys"
              :key="company.companyId"
              :label="company.companyName"
              :value="company.companyId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormSingle">确 定</el-button>
        <el-button @click="updateCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listQwPushCount,
  getQwPushCount,
  delQwPushCount,
  addQwPushCount,
  updateQwPushCount,
  exportQwPushCount
} from "@/api/qw/qwPushCount";
import {getCompanyList} from "@/api/company/company";

export default {
  name: "QwPushCount",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定义销售推送不同类型的企业消息的次数表格数据
      qwPushCountList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSingle: false,
      pushCountTypeList: [],
      pushCountStatusList: [],
      companys: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        pushCount: null,
        companyId: null,
        status: null
      },
      // 表单参数
      form: {
        companyIdList: []
      },
      // 表单校验
      rules: {
        type: [
          {required: true, message: '推送类型不能为空', trigger: 'change'}
        ],
        pushCount: [
          {required: true, message: '限定次数不能为空', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('限定次数不能为空'));
              } else if (isNaN(Number(value))) {
                callback(new Error('请输入有效的数字'));
              } else if (Number(value) < 0) {
                callback(new Error('次数不能为负数'));
              } else if (!Number.isInteger(Number(value))) {
                callback(new Error('请输入整数'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_qwSopAi_contentType").then(response => {
      this.pushCountTypeList = response.data;
    });

    this.getDicts("sys_company_status").then(response => {
      this.pushCountStatusList = response.data;
    });

    getCompanyList().then(response => {
      this.companys = response.data;
    });
  },
  methods: {
    // 公司选择变化事件
    handleCompanyChange(selectedCompanyIds) {
    },
    getCompanyNameById(companyId) {
      if (!companyId) return '-';
      const company = this.companys.find(item => item.companyId === companyId);
      return company ? company.companyName : '未知公司';
    },
    /** 查询定义销售推送不同类型的企业消息的次数列表 */
    getList() {
      this.loading = true;
      listQwPushCount(this.queryParams).then(response => {
        this.qwPushCountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //修改取消
    updateCancel() {
      this.openSingle = false;
      this.reset();
    },


    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        pushCount: null,
        companyId: null,
        status: 0,
      };
      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
      getQwPushCount(id).then(response => {
        this.form = response.data;
        this.openSingle = true;
        this.title = "修改企微推送信息次数";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQwPushCount(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQwPushCount(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.msgError("新增部分限定类型已存在:失败条数"+error.data().size());
            });
          }
        }
      });
    },

    /** 修改时不能批量选择公司名 */
    submitFormSingle() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQwPushCount(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.openSingle = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除定义销售推送不同类型的企业消息的次数编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delQwPushCount(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有定义销售推送不同类型的企业消息的次数数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportQwPushCount(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>
