<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板标题" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模板类型" prop="sendType">
        <el-select v-model="queryParams.sendType" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in sysQwSopType"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="queryParams.sort"
          placeholder="请输入排序"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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:sopTemp:add']"-->
        <!--        >新增</el-button>-->

        <el-dropdown
          v-if="roles.includes('add_sop_temp')"
          @command="handleCommand"
          trigger="click"
          placement="bottom-start"
        >
          <el-dropdown-menu slot="dropdown" style="width: 120px;">
            <el-dropdown-item
              v-for="option in sysQwSopType"
              :key="option.dictValue"
              :command="option.dictValue"
            >
              <i :class="option.iconClass" style="margin-right: 10px;"></i>
              {{ option.dictLabel }}
            </el-dropdown-item>
          </el-dropdown-menu>
          <span class="el-dropdown-link">
              <el-button type="primary" icon="el-icon-plus" plain size="mini">
                新增模板
              </el-button>
            </span>
        </el-dropdown>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-if="roles.includes('del_sop_temp')"
          v-hasPermi="['qw:sopTemp: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:sopTemp:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="sopTempList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模板编号" align="center" prop="id"/>
      <el-table-column label="模板编号" align="center">
        <template slot-scope="scope">
          <el-tag v-for="item in companys" v-if="scope.row.companyId == item.companyId">{{item.companyName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="模板标题" align="center" prop="name"/>
      <el-table-column label="模板类型" align="center" prop="sendType">
        <template slot-scope="scope">
          <dict-tag :options="sysQwSopType" :value="scope.row.sendType"/>
        </template>
      </el-table-column>
      <el-table-column label="间隔天数" align="center" prop="gap"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="修改时间" align="center" prop="updateTime"/>
      <el-table-column label="排序" align="center" prop="sort"/>

      <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-connection"
            v-if="roles.includes('update_sop_temp')"
            @click="copyTemplate(scope.row)"
            v-hasPermi="['qw:sopTemp:edit']"
          >复制模板
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleQueryDetails(scope.row)"
            v-hasPermi="['qw:sopTemp:list']"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="roles.includes('update_sop_temp')"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qw:sopTemp:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate2(scope.row)"
            v-if="roles.includes('update_sop_temp')"
            v-hasPermi="['qw:sopTemp:edit']"
          >管理规则
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateRed(scope.row)"
            v-if="scope.row.sendType == 5 && roles.includes('update_sop_temp_red')"
            v-hasPermi="['qw:sopTemp:edit']"
          >红包设置
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="roles.includes('del_sop_temp')"
            v-hasPermi="['qw:sopTemp: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="name">
          <el-input v-model="form.name" placeholder="请输入模板标题"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属项目" prop="project" v-if="form.sendType != 5">
          <el-select v-model="form.project" placeholder="请选择项目" filterable clearable size="small">
            <el-option
              v-for="dict in projectOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="courseId" v-if="form.sendType == 5 && !form.id">
          <el-select v-model="form.courseId"placeholder="请选择课程" style=" margin-right: 10px;" size="mini" filterable>
            <el-option
              v-for="dict in courseList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="间隔天数" prop="gap">
          <el-input-number v-model="form.gap" :min="1" label="间隔天数"></el-input-number>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" label="排序"></el-input-number>
        </el-form-item>
        <el-form-item label="每天发送次数" prop="num" v-if="form.sendType == 5 && !form.id">
          <el-input-number v-model="form.num" :min="1" label="每天发送次数" @change="sendNumChange"></el-input-number>
        </el-form-item>
        <el-form-item label="发送时间" v-if="form.sendType == 5 && !form.id">
          <el-time-picker
            v-for="item in form.timeList"
            class="custom-input"
            v-model="item.value"
            value-format="HH:mm"
            format="HH:mm"
            :picker-options="{ selectableRange: startTimeRange }"
            placeholder="时间"
            style="width: 100px;height: 20px;margin-left: 10px;margin-top: 10px">
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="float: right;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="课程红包" :visible.sync="redData.open" width="900px" append-to-body>
      <el-table v-loading="redData.loading" border :data="redData.list" height="500px">
        <el-table-column label="小节" align="left" prop="videoName"/>
        <el-table-column label="金额" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.redPacketMoney" :min="0.01" step="0.01" label="红包金额"></el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="float: right;">
        <el-button type="primary" @click="updateRedData" :disabled="redData.loading">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addTemp,
  copyTemplate,
  delSopTemp,
  exportSopTemp,
  getSopTemp,
  listSopTemp,
  getSelectableRange,
  redList,
  shareSopTemp,
  updateRedPackage,
  updateTemp
} from "@/api/qw/sopTemp";
import {getCompanyList} from "@/api/company/company";
import {courseList, getRoles} from "@/api/qw/sop";

export default {
  name: "SopTemp",
  data() {
    return {
      // 遮罩层
      loading: true,
      companysloading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      courseList: [],
      roles: [],
      //选中的公司
      companys: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      companyTotal: 0,
      total: 0,
      sendType: 0,
      // sop模板表格数据
      sopTempList: [],
      sysQwSopType: [],
      companyList: [],
      projectOptions: [],
      startTimeRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      command: 0,
      // 状态字典
      statusOptions: [],

      shareOptions: {
        title: '分享模板',
        open: false,
        templateId: null,
      },
      redData: {
        open: false,
        loading: true,
        list: [],
      },
      queryCompanyParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        status: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        setting: null,
        status: '1',
        sort: null,
        companyId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: '名称不能为空', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '状态不能为空', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '排序不能为空', trigger: 'blur'}
        ],
        gap: [
          {required: true, message: '间隔天数不能为空', trigger: 'blur'}
        ],
      },
      contentRules: {
        time: [{required: true, message: '时间不能为空', trigger: 'blur'}],
      }
    };
  },
  created() {
    this.getList();
    getRoles().then(res => {
      this.roles = res.data;
    })
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });

    getSelectableRange().then(e => {
      this.startTimeRange = e.data;
    })
    this.getDicts("sys_course_project").then(response => {
      this.projectOptions = response.data;
    });

    this.getDicts("sys_qw_sop_type").then(response => {
      this.sysQwSopType = response.data;
    });

    courseList().then(response => {
      this.courseList = response.list;
    });

    getCompanyList().then(response => {
      this.companys = response.data;
    });
  },
  methods: {

    handleCompanyQuery() {
      this.queryCompanyParams.pageNum = 1;
    },
    resetCompanyQuery() {
      this.resetForm("queryCompanyForm");
      this.handleCompanyQuery();
    },
    /** 查询sop模板列表 */
    getList() {
      this.loading = true;
      listSopTemp(this.queryParams).then(response => {
        this.sopTempList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        gap: 1,
        sendType: this.sendType,
        sort: 0,
        num: 1,
        timeList: [{value: ""}],
        status: "1",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleCommand(command) {
      // if (command==4) {
      //   this.$router.push('/qw/sopTemp/addAiChatTemp')
      // }else{
      this.sendType = command;
      this.title = "新增";
      this.reset();
      this.open = true;
      // this.$router.push('/qw/sopTemp/addTemp/'+command)
      // }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //销售公司多选
    handleSelectionCompany(selection) {
      this.companys = selection.map(item => item.companyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    // handleAdd() {
    //   this.$router.push('/qw/sopTemp/addSopTemp')
    // },
    /**
     * 查看详情
     */
    handleQueryDetails(row) {
      // if (row.sendType==4) {
      //   this.$router.push(`/qw/sopTemp/updateAiChatTemp/${row.id}/3`)
      // }else{
      this.$router.push(`/qw/sopTemp/updateSopTemp/${row.id}/3`)
      // }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // if (row.sendType==4) {
      //   this.$router.push(`/qw/sopTemp/updateAiChatTemp/${row.id}/1`)
      // }else{
      this.getInfo(row.id, 1);
      // this.$router.push(`/qw/sopTemp/updateTemp/${row.id}/1`)
      // }

    },
    /** 修改按钮操作 */
    handleUpdate2(row) {
      // if (row.sendType==4) {
      //   this.$router.push(`/qw/sopTemp/updateAiChatTemp/${row.id}/1`)
      // }else{
      let url = `/qw/sopTemp/updateSopTemp/${row.id}/1`;
      console.info(url)
      this.$router.push(url)
      // }
    },
    /** 修改按钮操作 */
    handleUpdateRed(row) {
      this.redData.open = true;
      redList(row.id).then(e => {
        this.redData.loading = false;
        this.redData.list = e.data;
      })
    },
    /** 修改按钮操作 */
    updateRedData() {
      this.redData.loading = true;
      updateRedPackage({list: this.redData.list}).then(e => {
        this.redData.open = false;
        this.getList();
      }).catch(() => {
        this.redData.loading = false;
      });
    },

    /** 分享模板 */
    shareTemplate(row) {
      this.shareOptions.open = true;
      this.shareOptions.templateId = row.id;
    },
    /**
     * 复制模板
     */
    copyTemplate(row) {
      // if(row.sendType==4){
      //   this.$router.push(`/qw/sopTemp/updateAiChatTemp/${row.id}/2`)
      // }else{
      this.getInfo(row.id, 2);
      // this.$router.push(`/qw/sopTemp/updateSopTemp/${row.id}/2`)
      // }
    },
    getInfo(id, command) {
      getSopTemp(id).then(response => {
        this.command = command;
        if (command == 2) {
          this.title = "复制";
        }
        if (command == 1) {
          this.title = "修改";
        }
        this.form = response.data;
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      delete this.form.rules
      this.$refs["form"].validate(valid => {
        if (valid) {
          let f = JSON.parse(JSON.stringify(this.form));
          if (f.timeList && f.timeList.length > 0) {
            f.timeList = f.timeList.map(item => item.value);
          }
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          if (this.command == 2) {
            copyTemplate(f).then(response => {
              this.msgSuccess("复制成功");
              this.open = false;
              loading.close();
              this.getList();
            });
          } else {
            if (f.id != null) {
              updateTemp(f).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                loading.close();
                this.getList();
              });
            } else {
              addTemp(f).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                loading.close();
                this.getList();
              });
            }
          }
        }
      });
    },

    handleShareTemplate() {
      const companyIds = this.companys;
      let templateId = this.shareOptions.templateId;
      this.$confirm("确定将模板分享给 公司编号为：" + companyIds + "的公司？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return shareSopTemp({companyIds: companyIds, templeId: templateId});
      }).then(() => {
        this.companys = [];
        this.shareOptions.open = false;
        this.getList();
        this.msgSuccess("分享成功");
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除sop模板编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delSopTemp(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有sop模板数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportSopTemp(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    sendNumChange(val, old) {
      if (val > old) {
        for (let i = 0; i < val - old; i++) {
          this.form.timeList.push({value: ""});
        }
      } else {
        let len = old - val;
        this.form.timeList.splice(Math.max(this.form.timeList.length - len, 0), len);
      }
    }
  }
};
</script>
