<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="企微公司" prop="corpId">
                  <el-select v-model="queryParams.corpId" placeholder="企微公司" size="small" @change="updateCorpId()">
                    <el-option
                      v-for="dict in myQwCompanyList"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
                  </el-select>
          </el-form-item>
      <el-form-item label="类型 " prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small"  @change="updateCorpId()" >
          <el-option
            :key="1"
            :label="'个微'"
            :value="1"
          />
          <el-option
            :key="2"
            :label="'企微'"
            :value="2"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规则状态 " prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择规则状态" clearable size="small"  @change="updateCorpId()" >
          <el-option
            :key="0"
            :label="'停用'"
            :value="0"
          />
          <el-option
            :key="1"
            :label="'待执行'"
            :value="1"
          />
          <el-option
            :key="2"
            :label="'已完成'"
            :value="2"
          />
          <el-option
            :key="3"
            :label="'已完成无满足条件的人'"
            :value="3"
          />
        </el-select>
      </el-form-item>
      <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="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="success"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['qw:sop:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          plain
          type="warning"
          icon="el-icon-edit"
          :disabled="multiple"
          @click="handleExecute"
          v-hasPermi="['qw:sop:execute']"
        >批量执行SOP</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="id" />
      <el-table-column label="规则名称" align="center" prop="name" />
      <el-table-column label="规则状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag  type="warning" v-if="scope.row.status==1">待执行</el-tag>
          <el-tag type="info" v-else-if="scope.row.status==0">停用</el-tag>
          <el-tag type="success" v-else-if="scope.row.status==2">已完成</el-tag>
          <el-tag type="success" v-else-if="scope.row.status==3">已完成无满足条件</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.type==1">个微</el-tag>
          <el-tag type="primary" v-else-if="scope.row.type==2">企微</el-tag>
        </template>
      </el-table-column>
      <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="qwUserIds">
        <template slot-scope="scope">
            <div v-if="scope.row.type==2" v-for="id in scope.row.qwUserIds.split(',')" :key="id" style="display: inline;" class="text-container">
                <el-tag type="success" v-for="list in companyUserList" :key="list.qwUserId" style="margin: 3px;" v-if="list.id==id">{{list.qwUserName}}</el-tag>
            </div>
            <div v-if="scope.row.type==1" v-for="id in scope.row.qwUserIds.split(',')" :key="id" style="display: inline;" class="text-container">
              <el-tag type="success" v-for="list in companyUserLists" :key="list.userId" style="margin: 3px;" v-if="list.userId==id">{{list.nickName}}</el-tag>
            </div>
        </template>
      </el-table-column>

      <el-table-column label="模板" align="center" prop="tempId" >
        <template slot-scope="scope">
            <div v-for="id in tempList" v-if="id.id==scope.row.tempId">{{id.name}}</div>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expiryTime" >
        <template slot-scope="scope">
          {{scope.row.expiryTime}} 小时
        </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
            v-if="scope.row.status==2"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
            v-hasPermi="['qw:sop:list']"
          >执行详情</el-button>
          <el-button
            v-if="scope.row.status!=2"
            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="type">
         <el-radio-group v-model="form.type">
             <el-radio
               :label="1"
             >个微</el-radio>
             <el-radio
               :label="2"
             >企微</el-radio>
         </el-radio-group>
         </el-form-item>

<!--        <div v-if="form.type==2">-->

<!--        <el-form-item label="推送方式 ">-->
<!--          <el-radio-group v-model="form.sendType" @input="handleSendTypeChange">-->
<!--            <el-radio-->
<!--              v-for="dict in sysQwSopType"-->
<!--              :key="dict.dictValue"-->
<!--              :label="parseInt(dict.dictValue)"-->
<!--            >{{dict.dictLabel}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
<!--          <el-form-item label="选择员工" prop="qwUserIds" style="margin-top: 2%">-->
<!--            <div>-->
<!--              <el-button-->
<!--                size="medium"-->
<!--                icon="el-icon-circle-plus-outline"-->
<!--                plain-->
<!--                @click="handlelistUser(form.type,form.sendType)">请选择使用员工</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 companyUserList" :key="list.qwUserId" v-if="list.id==id">{{list.qwUserName}}</span>-->
<!--              </el-tag>-->
<!--            </div>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="标签规则" prop="filterType">-->
<!--            <el-radio-group v-model="form.filterType">-->
<!--              <el-radio-->
<!--                :label="1"-->
<!--              >含全部标签</el-radio>-->
<!--              <el-radio-->
<!--                :label="2"-->
<!--              >含任意标签</el-radio>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="选择的标签" prop="tags">-->
<!--            <el-select v-model="tags" remote multiple placeholder="请选择" filterable  style="width: 100%;">-->
<!--              <el-option-->
<!--                v-for="dict in tagList"-->
<!--                :label="dict.name"-->
<!--                :value="dict.tagId">-->
<!--              </el-option>-->
<!--            </el-select>-->

<!--          </el-form-item>-->
<!--          <el-form-item label="排除的标签" prop="excludeTags">-->
<!--            <el-select v-model="excludeTags" remote multiple placeholder="请选择" filterable  style="width: 100%;">-->
<!--              <el-option-->
<!--                v-for="dict in tagList"-->
<!--                :label="dict.name"-->
<!--                :value="dict.tagId">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </div>-->
<!--        <div v-if="form.type==1">-->
<!--          <el-form-item label="推送方式 ">-->
<!--            <el-tag type="success" v-model="form.sendType=2">AI插件</el-tag>-->
<!--          </el-form-item>-->
<!--        </div>-->

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable size="small"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="模板" prop="tempId">
          <el-select v-model="form.tempId"  @focus="selectListSopTemp(form.sendType)" placeholder="请选择模板" v-loading="tempListLoading"   >
            <el-option
              v-for="dict in tempList"
              :label="dict.name"
              :value="dict.id">
            </el-option>
            <div v-if="tempListLoading" slot="prefix" class="select-prefix">正在查询相应模板...</div>
          </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="listUser.title" :visible.sync="listUser.open" style="width: 1300px;height: 100%" append-to-body>
      <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
    </el-dialog>

    <!--  执行详情  -->
    <el-drawer :title="sopLogsDialog.title" :visible.sync="sopLogsDialog.open" size="70%" style="font-weight: bolder">
      <sopLogsDetails ref="sopLogsDetails" :rowDetailFrom="sopLogsDialog.sopLogsForm"></sopLogsDetails>
    </el-drawer>

  </div>
</template>

<script>
import {listSop, getSop, delSop, addSop, updateSop, exportSop, courseList, videoList, executeSop} from "@/api/qw/sop";
import { listSopTemp, getSopTemp, delSopTemp, addSopTemp, updateSopTemp, exportSopTemp } from "@/api/qw/sopTemp";
import {getQwAllUserList, listUser, qwList} from '@/api/company/companyUser'
import qwUserList from '@/views/qw/user/qwUserList.vue'
import ImageUpload from "@/views/qw/sop/ImageUpload";
import CustomerGroupDetails from '@/views/qw/groupMsg/customerGroupDetails.vue'
import sopLogsDetails from '@/views/qw/sopLogs/sopLogsList.vue'
import { listTag, getTag, } from "@/api/qw/tag";
import { getMyQwUserList,getMyQwCompanyList } from "@/api/qw/user";
import source from "echarts/src/data/Source";
export default {
  name: "Sop",
    components: { CustomerGroupDetails, qwUserList,ImageUpload,sopLogsDetails},
  data() {
    return {
      //模板查询
      tempListLoading:false,
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      //选中的map
      selectionMap:{},
      myQwCompanyList:[],
      //销售员工列表
      companyUserLists:[],
      courseList:[],
      // videoList:[],
      tags:null,
      excludeTags:null,
      // 非单个禁用
      single: true,
      setting:[],
      tagList:[],
      tempList:[],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企微sop表格数据
      sopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      companyUserList:[],
      // 状态字典
      statusOptions: [],

      //企微SOP发送类型
      sysQwSopType: [],

      //SOP课程观看状态
      sysFsSopWatchStatus:[],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        sendType:null,
        type: null,
        qwUserIds: null,
        setting: null,
        createBy: null,
        corpId: null,
        createTime: null
      },
      sopLogsDialog:{
        title:'',
        open:false,
        sopLogsForm:[],
      },
      // 表单参数
      form: {},
      userSelectList:[],
      listUser:{
        title:"",
        open:false
      },
      // 表单校验
      rules: {
        name:[ { required: true, message: "名称不能为空", trigger: "submit" }],
        type:[ { required: true, message: "不能为空", trigger: "submit" }],
        sendType:[ { required: true, message: "不能为空", trigger: "submit" }],
        startTime:[ { required: true, message: "开始时间不能为空", trigger: "submit" }],
        tempId:[ { required: true, message: "模板不能为空", trigger: "submit" }],
      }
    };
  },
  created() {
    getMyQwCompanyList().then(response => {
        this.myQwCompanyList = response.data;
        if(this.myQwCompanyList!=null && this.myQwCompanyList.length>0){
          this.queryParams.corpId=this.myQwCompanyList[0].dictValue;
          this.refreshData(this.queryParams.corpId);
          this.getList();
        }
    });

    listUser().then(res => {
        this.companyUserLists = res.rows;
      }
    );

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

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

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

  },
  watch:{
    userSelectList(newList) {
      this.form.qwUserIds = newList.map(item => item.id);
    }
  },
  methods: {

     updateCorpId(){
       this.reset();
       this.refreshData(this.queryParams.corpId);
       this.getList();
     },

    //刷新部分数据
    refreshData(row){
      getQwAllUserList(row).then(response => {
        this.companyUserList = response.data;
      });

      listTag({corpId:row}).then(response => {
        this.tagList = response.rows;
      });

    },

    //查询模板
    selectListSopTemp(type){
      this.tempListLoading = true; // 开始查询，显示加载提示
      listSopTemp({sendType:type}).then(response => {
        this.tempList = response.rows;
        this.tempListLoading = false;
      });
    },
    handlelistUser(type,sendType){

       setTimeout(() => {
         this.$refs.QwUserList.getDetails(this.queryParams.corpId,type,sendType);
       }, 1);
       this.listUser.title="选择企业成员"
       this.listUser.open=true;

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

    },
    addContent(index){
      // this.setting[index].content.push({type:1})
      if (this.form.sendType==2){
        this.setting[index].content.push({ type: 1 });
      }else {
        if (this.setting[index].content.length < 9) {
          this.setting[index].content.push({ type: 1 });
        } else {
          this.$message({
            message: '最多只能添加 9 个内容',
            type: 'warning'
          });
        }
      }

    },

    //选择变动时的变动
    handleSendTypeChange(val){
      this.tempList=[];
      this.form.tempId=null;
      if (val==1) {
        // 遍历 this.setting 数组并清空每个对象的 content 属性
        this.setting.forEach(item => {
          if (item.content.length > 9) {
            item.content = item.content.slice(0, 9); // 保留前 9 个元素
          }
        });
      }
    },
    delContent(index,contentIndex){
      this.setting[index].content.splice(contentIndex,1)
    },

    //添加SOP规则类型
    handleCommand(command){
      this.setting.push({sopType:command,ruleType:null,name:null,type:1,content:[],isBindUrl:1,url:null,day:"0",hour:"0",minute:"0",time:""})
    },

    //添加课程SOP
    handleCrouseCommand(command,val){
      console.log("command",command)
      console.log("val",val)
    },

    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;

        listSopTemp().then(response => {
          this.tempList = response.rows;
        });

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // courseChange(){
    //   videoList(this.form.courseId).then(response => {
    //     this.videoList = response.list;
    //   });
    // },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: 1,
        sendType:2,
        type: 2,
        filterType:2,
        qwUserIds: null,
        corpId: null,
        setting: null,
        createBy: null,
        createTime: null
      };
      this.resetForm("form");
      this.tags = null;
      this.excludeTags = null;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.corpId=this.myQwCompanyList[0].dictValue;
      this.refreshData(this.queryParams.corpId);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selectionMap=selection;
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$router.push('/qw/sop/addSop/'+this.queryParams.corpId)
      // this.open = true;
      // this.setting=[]
      // this.userSelectList=[]
      // this.title = "添加企微sop";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push('/qw/sop/upDateSop/'+row.id)
    },
    // /** 修改按钮操作 */
    // 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.qwUserIds.split(",");
    //     this.tags = this.form.tags.split(",");
    //     this.excludeTags = this.form.excludeTags.split(",");
    //
    //     if (this.form.setting!=null){
    //       this.setting=JSON.parse(this.form.setting);
    //     }
    //
    //     listSopTemp({id:this.form.tempId}).then(response => {
    //       this.tempList = response.rows;
    //     });
    //
    //     // this.courseChange();
    //     this.title = "修改企微sop";
    //   });
    // },

    /**
    * 查看详情
    */
    handleDetail(row){
        this.sopLogsDialog.title='规则执行详情';
        this.sopLogsDialog.open=true;
        this.sopLogsDialog.sopLogsForm=row;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.userSelectList.length<=0){
            return this.$message("请选择员工")
          }
          this.form.qwUserIds = this.userSelectList.join(",");
          this.form.corpId=this.queryParams.corpId;
          if (this.tags!=null){
            this.form.tags=(this.tags).toString()
          }
          if (this.excludeTags!=null){
            this.form.excludeTags=(this.excludeTags).toString()
          }

          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(() => {});
    },
    /**
    * 批量执行SOP任务
    */
    handleExecute(){

      // // 获取选中的数据中 状态未发送的SOP
      // const ids = this.selectionMap
      //   .filter(item => item.status === 1) // 过滤出 status 为 1 的项
      //   .map(item => item.id); // 提取这些项的 id
      //
      // this.$confirm('是否确认立即执行sop编号为"' + ids + '"的数据项?', "警告【只能立即执行（待执行的）】", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(function() {
      //   this.loading=true;
      //   return executeSop(ids);
      // }).then(() => {
      //   this.getList();
      //   this.msgSuccess("执行完成");
      // }).catch(() => {});
      //
      // this.loading=false;
      // 获取选中的数据中 状态未发送的SOP
      const ids = this.selectionMap
        .filter(item => item.status === 1)
        .map(item => item.id);

      this.$confirm('是否确认立即执行sop编号为"' + ids + '"的数据项?', "警告【只能立即执行（待执行的）】", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return executeSop(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("执行完成");
      }).catch(() => {

      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    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;
  display: block;
}
.custom-input /deep/ .el-input__icon {
  line-height: 20px;
}
</style>
