<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="createTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择创建时间">
        </el-date-picker>
      </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:sop:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qw:sop:edit']"
        >修改</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:sop: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:sop:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="sopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规则名称" align="center" prop="name" />
      <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="ids" >
        <template slot-scope="scope">
            <div v-for="id in scope.row.ids.split(',')" :key="id" style="display: inline;" class="text-container">
              <el-tag type="success" v-for="list in GroupList"  style="margin: 3px;" v-if="list.chatId==id">{{list.name}}</el-tag>
            </div>
        </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <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:sop:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qw:sop: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"
    />

    <!-- 添加或修改企微sop对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <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="parseInt(dict.dictValue)"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
         </el-form-item>
        <el-form-item label="选择群：" prop="ids" style="margin-top: 2%">
            <div>
              <el-button
                size="medium"
                icon="el-icon-circle-plus-outline"
                plain
                @click="handlelistUser">请选择群</el-button>
            </div>
            <div>
              <el-tag
                style="margin-left: 5px"
                size="medium"
                :key="id"
                v-for="id in userSelectList"
                closable
                :disable-transitions="false"
                @close="handleClosegroupUser(id)">
                <span v-for="list in GroupList" :key="list.chatId" v-if="list.chatId==id">{{list.name}}</span>
              </el-tag>
            </div>
        </el-form-item>

        <el-form-item label="规则" prop="setting">
          <div v-for="(item, index) in setting"    >
            <el-row>
              <el-col :span="22">
                <div style="background-color: #fbfbfb;padding: 15px;  border: 1px solid #e6e6e6; margin-bottom: 20px;">
                  <el-form :model="item"  label-width="80px">
                    <el-form-item label="内容名称"  style="height: 50px;">
                       <el-input v-model="item.name" placeholder="内容名称,仅内部可见" />
                    </el-form-item>
                    <el-form-item label="发送时间" prop="week" >
                       <el-radio-group v-model="item.type" class="custom-input">
                         <el-radio :label="1"  style="margin-bottom: 10px;margin-top: 10px;">
                           客户添加客服后
                           <el-input v-model="item.hour"  style="width: 40px;" onkeyup="value=value.replace(/[^0-9]/g,'')"/>
                           小时
                           <el-input v-model="item.minute"  style="width: 40px;" onkeyup="value=value.replace(/[^0-9]/g,'')"/>
                           分钟后发送提醒
                           </el-radio>
                         <el-radio :label="2" style="margin-bottom: 10px;">
                           客户添加客服后
                           <el-input v-model="item.day"  style="width: 40px;" onkeyup="value=value.replace(/[^0-9]/g,'')"/>
                           天后,当日
                           <el-time-picker
                             class="custom-class"
                             v-model="item.time"
                             value-format="HH:mm"
                             format="HH:mm"
                             :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
                             placeholder="时间"
                             style="width: 80px;height: 20px;">
                           </el-time-picker>
                           发送提醒
                         </el-radio>
                       </el-radio-group>
                    </el-form-item>
                    <el-form-item label="发送内容"  >
                       <div v-for="(content, contentIndex) in item.content">
                         <el-row>
                           <el-col el-col :span="22" >
                             <el-radio-group v-model="content.type">
                                 <el-radio
                                   :label="1"
                                 >文字</el-radio>
                                 <el-radio
                                   :label="2"
                                 >图片</el-radio>
                             </el-radio-group>
                             <el-input v-if="content.type==1" v-model="content.value" type="textarea" placeholder="内容" />
                             <ImageUpload v-if="content.type==2" v-model="content.imgUrl" type="image" :num="1" :width="150" :height="150" />
                           </el-col>
                           <el-col :span="1" :offset="1">
                             <i class="el-icon-delete" @click="delContent(index,contentIndex)" style="margin-top: 20px;" v-if="item.content.length>1"></i>
                           </el-col>
                         </el-row>
                       </div>
                       <el-link type="primary" class="el-icon-plus" :underline="false" @click='addContent(index)'>添加内容</el-link>
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
              <el-col :span="1" :offset="1">
                 <i class="el-icon-delete-solid" @click="delSetting(index)"  v-if="setting.length>1"></i>
              </el-col>
            </el-row>
          </div>
           <el-link type="primary" class="el-icon-plus" :underline="false" @click='addSetting()'>添加规则</el-link>
        </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="listUser.title" :visible.sync="listUser.open" style="width: 1300px;height: 100%" append-to-body>
      <GroupChat ref="GroupChat" @selectGroupChatList="selectGroupChatList" ></GroupChat>
    </el-dialog>
  </div>
</template>

<script>
import { listSop, getSop, delSop, addSop, updateSop, exportSop } from "@/api/qw/sop";
import GroupChat from '@/views/qw/autoTags/groupChat.vue'
import { allList } from '@/api/qw/groupChat'
import ImageUpload from "@/views/qw/sop/ImageUpload";
export default {
  name: "Sop",
    components: { GroupChat,ImageUpload},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      setting:[],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企微sop表格数据
      sopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      GroupList:[],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        type: 2,
        ids: null,
        setting: null,
        createBy: null,
        createTime: null
      },
      // 表单参数
      form: {},
      userSelectList:[],
      listUser:{
        title:"",
        open:false
      },
      // 表单校验
      rules: {
        name:[ { required: true, message: "名称不能为空", trigger: "submit" }],
        status:[ { required: true, message: "不能为空", trigger: "submit" }],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
    allList().then(response => {
        this.GroupList = response.data;
      });
  },
  watch:{
    userSelectList(newList) {
      this.form.ids = newList.map(item => item.id);
    }
  },
  methods: {
    handlelistUser(){
      this.listUser.title="选择企业成员"
      this.listUser.open=true;
    },

    selectGroupChatList(list){

      this.listUser.open=false;
      list.forEach(obj => {
        if (!this.userSelectList.some(item => item == obj.chatId)) {
          this.userSelectList.push(obj.chatId);
        }
      });
    },

    addContent(index){
      this.setting[index].content.push({type:1})
    },
    delContent(index,contentIndex){
      this.setting[index].content.splice(contentIndex,1)
    },
    addSetting(){
      this.setting.push({name:null,type:1,content:[],day:"0",hour:"0",minute:"0",time:""})
    },
    delSetting(index){
      this.setting.splice(index,1)
    },
    handleClosegroupUser(list){
      const index = this.userSelectList.findIndex(t => t === list);
      if (index !== -1) {
        this.userSelectList.splice(index, 1);
      }
    },
    /** 查询企微sop列表 */
    getList() {
      this.loading = true;
      listSop(this.queryParams).then(response => {
        this.sopList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: 1,
        type: null,
        ids: null,
        setting: null,
        createBy: null,
        createTime: null
      };
      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.setting=[]
      this.userSelectList=[]
      this.title = "添加企微sop";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSop(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.userSelectList = this.form.ids.split(",");
        this.setting=JSON.parse(this.form.setting);
        this.title = "修改企微sop";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.type = 2
          if(this.userSelectList.length<=0){
            return this.$message("请选择员工")
          }
          this.form.ids = this.userSelectList.join(",");
          if(this.setting.length<=0){
            return this.$message("请添加规则")
          }
          for (let i = 0; i < this.setting.length; i++) {
            if(this.setting[i].name==null||this.setting[i].name==""){
              return this.$message("内容名称不能为空")
            }
            if(this.setting[i].type==1){
              if(this.setting[i].hour==null||this.setting[i].hour==""||this.setting[i].minute==null||this.setting[i].minute==""){
                return this.$message("时间不能为空")
              }
            }else if(this.setting[i].type==2){
              if(this.setting[i].day==""||this.setting[i].time==null||this.setting[i].time==""){
                return this.$message("时间不能为空")
              }
            }
            var content= this.setting[i].content
            if(content.length>0){
               for (let j = 0; j < content.length; j++) {
                 if(content[j].type==1){
                   if(content[j].value==null||content[j].value==""){
                      return this.$message("发送内容不能为空")
                   }
                 } else if(content[j].type==2){
                   if(content[j].imgUrl==null||content[j].imgUrl==""){
                      return this.$message("发送图片不能为空")
                   }
                 }
               }


            }else{
              return this.$message("发送内容不能为空")
            }
          }

          this.form.setting=JSON.stringify(this.setting)
          if (this.form.id != null) {
            updateSop(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSop(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除企微sop编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSop(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企微sop数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportSop(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style scoped>
.custom-input /deep/ .el-input__inner {
  height: 20px;
  padding: 0 4px;
  text-align:center;

}
.custom-input /deep/ .el-input__icon {
  line-height: 20px;
}
</style>
