<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-dropdown
          @command="handleCommand"
          trigger="click"
          placement="bottom-start"
        >
          <el-dropdown-menu slot="dropdown" style="width: 140px;">
            <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"
                v-hasPermi="['app:template:add']"
              >
                新增模板
              </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-hasPermi="['app:template:delete']"
        >删除</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="['app:template: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" 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"
            @click="copyTemplate(scope.row)"
            v-hasPermi="['app:template:copy']"
          >复制模板</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-share"
            @click="shareTemplate(scope.row)"
            v-hasPermi="['app:template:share']"
          >分享模板</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleQueryDetails(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['app:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate2(scope.row)"
            v-hasPermi="['app:template:rule']"
          >管理规则</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateImageFun(scope.row.id)"
            v-hasPermi="['app:template:updateImage']"
          >更新图片</el-button>
          <el-button
            :disabled="scope.row.status == 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:template:stop']"
          >停用</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="gap" v-show="false">
          <el-input-number v-model="form.gap"  :min="1" label="间隔天数"></el-input-number>
          <div style="color: #999;font-size: 14px;display: flex;align-items: center;">
            <i class="el-icon-info"></i>
            设置间隔几天发送sop任务模板内容。比如 设置间隔2天。则第一天，第三天，第五天时 才发送科普模板中的第一天，第二天，第三天的内容。（默认建议1天,好精准匹配不迷糊）
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort" v-show="false">
          <el-input-number v-model="form.sort"  :min="0" label="排序"></el-input-number>
        </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>
    
  </div>
</template>

<script>
import {
  listSopTemp,
  getSopTemp,
  delSopTemp,
  updateTemp,
  copyTemplate,
  addTemp,
  updateImage,
  exportSopTemp,
  shareSopTemp
} from "@/api/app/sop/template";
export default {
  name: "sopTemplate",
  data() {
    return {
      // 遮罩层
      loading: true,
      companysloading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      //选中的公司
      companys:[],
      deptOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      companyTotal: 0,
      total:0,
      sendType:0,
      // sop模板表格数据
      sopTempList: [],
      sysQwSopType:[],
      companyList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      command: 0,
      // 状态字典
      statusOptions: [],

      shareOptions:{
        title:'分享模板',
        open:false,
        templateId:null,
      },
      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' }
        ],
        // createByDept:[
        //   { required: true, message: '归属部门不能为空', trigger: 'blur' }
        // ]
      },
      contentRules:{
        time:[{ required: true, message: '时间不能为空', trigger: 'blur' }],
      }
    };
  },
  created() {
    this.getList();

    // this.getDeptTreeSelect();
    this.getDicts("app_normal_disabled_status").then(response => {
      this.statusOptions = response.data;
    });

    // this.getCompanyList();

    this.getDicts("app_sop_type").then(response => {
      this.sysQwSopType = response.data;
    });
  },
  methods: {
    updateImage,
    handleCompanyQuery(){
      this.queryCompanyParams.pageNum = 1;
      this.getCompanyList();
    },
    resetCompanyQuery(){
      this.resetForm("queryCompanyForm");
      this.handleCompanyQuery();
    },

    getDeptTreeSelect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },

    /** 查询企业列表 */
    getCompanyList() {
      this.companysloading = true;
      listCompany(this.queryCompanyParams).then(response => {
        this.companyList = response.rows;
        this.companyTotal = response.total;
        this.companysloading = false;
      });
    },
    /** 查询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,
        status: "1",
        createByDept:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    updateImageFun(id){

      let loadingRock = this.$loading({
        lock: true,
        text: '正在执行中请稍后~~请不要刷新页面！！',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      updateImage(id).then(response => {
        this.getList();
        this.$message.success("更新图片 完成！");
      }).finally(res=>{
        loadingRock.close();
      })


    },
    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(`/user/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{
          this.$router.push(`/user/sopTemp/updateSopTemp/${row.id}/1`)
        // }

    },

    /** 分享模板 */
    shareTemplate(row) {
      return this.msgError('该功能暂未开通！');
      // 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) {
          if(this.command == 2){
            copyTemplate(this.form).then(response => {
              this.msgSuccess("复制成功");
              this.open = false;
              this.getList();
            });
          }else{
            if (this.form.id != null) {
              updateTemp(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addTemp(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                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(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
  ::v-deep  .el-dialog__footer {
    height: 55px;
  }
</style>