<template>
  <div class="app-container">
    <div style="margin: 30px;">聊天sop任务</div>
    <div style="margin-top: 10px;margin-left: 50px;margin-right: 100px;margin-bottom: 60px;">

      <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" @change="clearUser">
            <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">

            <el-radio

              v-for="dict in sysQwSopType.filter(item => parseInt(item.dictValue) === 4)"

              :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 companyQwUserList" :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>
          <el-form-item label="选择员工" prop="qwUserIds" style="margin-top: 2%">
            <div>
              <el-button
                size="medium"
                icon="el-icon-circle-plus-outline"
                plain
                @click="handleCompanyUser(form.type,form.sendType)">请选择使用员工</el-button>
            </div>
            <div>
              <el-tag
                style="margin-left: 5px"
                size="medium"
                :key="userId"
                v-for="userId in userSelectList"
                closable
                :disable-transitions="false"
                @close="handleClosegroupUser(userId)">
                <span v-for="list in companyUserLists " :key="list.userId" v-if="list.userId==userId">{{list.nickName}}</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 wxUserGroupList"
                :label="dict.groupName"
                :value="dict.groupId">
              </el-option>
            </el-select>

          </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="expiryTime">
          <el-row>
            <el-input-number  v-model="form.expiryTime"  :min="1" :max="100" ></el-input-number>
            （小时）
          </el-row>
        </el-form-item>
        <el-form-item v-if="form.sendType==2" label="自动添加SOP" prop="autoSopTime.autoSopType" >
          <el-radio-group v-model="form.autoSopTime.autoSopType">
            <el-radio
              :label="1"
            >当天开始</el-radio>
            <el-radio
              :label="2"
            >次日开始</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="display: flex; align-items: center; flex-wrap: nowrap;">
          <div v-if="form.autoSopTime.autoSopType==1" style="display: flex; align-items: center">
            <el-form-item
              label="起始时间"
              prop="autoStartTime"
              label-width="100px"
              style="margin: 2% 0;align-items: center;">
              <el-time-select
                style="width: 120px;"
                placeholder="起始时间"
                v-model="form.autoSopTime.autoStartTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00'
                }">
              </el-time-select>
            </el-form-item>
            <el-form-item
              label="结束时间"
              prop="autoEndTime"
              label-width="100px"
              style="margin: 2% 0; align-items: center; ">
              <el-time-select
                style="width: 120px;"
                placeholder="结束时间"
                v-model="form.autoSopTime.autoEndTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00',
                  minTime: form.autoSopTime.autoEndTime
                }">
              </el-time-select>
            </el-form-item>
          </div>
        </div>
        <el-form-item  v-if="form.autoSopTime.autoSopType==1" label="过期消息是否发送" prop="autoSopSend"  label-width="130px">
          <el-radio-group v-model="form.autoSopTime.autoSopSend">
            <el-radio
              :label="1"
            >是</el-radio>
            <el-radio
              :label="2"
            >否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-alert
          v-if="form.autoSopTime.autoSopType==1"
          title="起始时间-结束时间之内的，当天立即创建SOP，时间之外的 次日创建SOP"
          type="warning"
          style="font-size: 15px; margin-top: 3%;"
          :closable="false"
          show-icon>
        </el-alert>
        <el-form-item label="模板" prop="tempId">
          <div @click="selectListSopTemp(form.sendType)" style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;">
            <el-tag v-if="form.tempId" type="success" style="margin: 3px;">
              {{ form.tempName }}
            </el-tag>
            <span v-else style="margin: 3px; color: #999;">请点我选择模板</span>
          </div>
        </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 :title="listUser.title" :visible.sync="listUser.open" style="width: 1300px;height: 100%" append-to-body>
      <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
    </el-dialog>

    <el-dialog :title="companyUser.title" :visible.sync="companyUser.open" style="width: 110%;height: 100%" append-to-body>
      <company-user-list ref="companyUserList" @selectCompanyUserList="selectCompanyUserList"></company-user-list>
    </el-dialog>

    <el-dialog title="选择模板"  :visible.sync="tempOpen" append-to-body  >
      <sop-temp ref="SopTempComments" @sopTemp="sopTemp"></sop-temp>
    </el-dialog>
    </div>
  </div>
</template>

<script>
import { listSop, getSop, delSop, addSop, updateSop, exportSop,courseList,videoList } 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 companyUserList from '@/views/company/companyUser/companyUserList.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 {listWxUserGroup, sopListWxUserGroup} from "@/api/wxUser/wxUserGroup";
import SopTemp from "@/views/qw/sopTemp/sopTemp.vue";
export default {
  name: "addSop",
  components: {SopTemp, CustomerGroupDetails, qwUserList,companyUserList,ImageUpload,sopLogsDetails},
  data() {
    return {
      //模板查询
      myQwCompanyList:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      //模板遮罩
      tempOpen:false,
      // 选中数组
      ids: [],
      courseList:[],
      // videoList:[],
      tags:null,
      excludeTags:null,
      // 非单个禁用
      single: true,
      setting:[],
      tagList:[],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企微sop表格数据
      sopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //企业微信员工列表
      companyQwUserList:[],

      //销售员工列表
      companyUserLists:[],
      // 状态字典
      statusOptions: [],

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

      sopLogsDialog:{
        title:'',
        open:false,
        sopLogsForm:[],
      },
      // 表单参数
      form: {
        status: 1,
        sendType:3,
        type: 2,
        filterType:2,
        expiryTime:1,
        isAutoSop:1,
        autoSopTime:{ autoSopType:2,autoStartTime:'00:00',autoEndTime:'24:00',autoSopSend:2},
      },
      userSelectList:[],
      //企业微信员工
      listUser:{
        title:"",
        open:false
      },
      //销售员工
      companyUser:{
        title:"",
        open:false
      },
      //个微客户的分组
      wxUserGroupList:[],
      // 表单校验
      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() {

    this.form.corpId= this.$route.params && this.$route.params.corpId;

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

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

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

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

    //个微客户的分组
    sopListWxUserGroup().then(response => {
      this.wxUserGroupList = response.rows;
    });
  },
  watch:{
    userSelectList(newList) {
      this.form.qwUserIds = newList.map(item => item.id);
    }
  },
  methods: {

    //刷新部分数据
    refreshData(row){

      getQwAllUserList(row).then(response => {
        this.companyQwUserList = response.data;
      });

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

    },

    //查询模板
    selectListSopTemp(type){
      this.tempOpen = true;
      setTimeout(() => {
        this.$refs.SopTempComments.getList(type);
      }, 200);

    },
    sopTemp(val){
      this.form.tempId=val.id
      this.form.tempName=val.name
      this.tempOpen=false;
    },
    //选择企微员工时
    handlelistUser(type,sendType){

      setTimeout(() => {

        this.$refs.QwUserList.getDetails(this.form.corpId,type,sendType);

      }, 1);

      this.listUser.title="选择企微员工"
      this.listUser.open=true;

    },
    //切换类别时 ，清除选择的成员
    clearUser(){
      this.userSelectList=[];
      this.tags=null;
    },

    //选择销售员工时
    handleCompanyUser(type,sendType){

      // setTimeout(() => {
      //
      //   // this.$refs.QwUserList.getDetails(this.form.corpId,type,sendType);
      //
      // }, 1);

      this.companyUser.title="选择销售"
      this.companyUser.open=true;

    },
    //企业微信员工
    selectUserList(list){
      this.listUser.open=false;
      list.forEach(obj => {
        if (!this.userSelectList.some(item => item == obj.id)) {
          this.userSelectList.push(obj.id);
        }
      });

    },

    //销售员工
    selectCompanyUserList(list){

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

    //选择变动时的变动
    handleSendTypeChange(val){
      this.userSelectList=[];
      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 个元素
          }
        });
      }
    },
    handleClosegroupUser(list){
      const index = this.userSelectList.findIndex(t => t === list);
      if (index !== -1) {
        this.userSelectList.splice(index, 1);
      }
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.replace('/qw/conversion/sop')
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: 1,
        sendType:2,
        type: 2,
        filterType:2,
        expiryTime:1,
        qwUserIds: null,
        corpId: null,
        setting: null,
        createBy: null,
        createTime: null,
        autoSopTime:{ autoSopType:2,autoStartTime:'00:00',autoEndTime:'24:00',autoSopSend:2},
      };
      this.resetForm("form");
      this.tags = null;
      this.excludeTags = null;
    },
    /** 重置按钮操作 */
    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";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.userSelectList.length<=0){
            return this.$message("请选择员工")
          }
          this.form.qwUserIds = this.userSelectList.join(",");
          if (this.tags!=null && this.tags.length>0 ){
            this.form.tags=(this.tags).toString()
          }else {
            return  this.$message.error("选择得标签不能为空！！请选择筛选的标签")
          }
          if (this.excludeTags!=null){
            this.form.excludeTags=(this.excludeTags).toString()
          }

          this.form.setting=JSON.stringify(this.setting)
          this.form.autoSopTime=JSON.stringify(this.form.autoSopTime)
          if (this.form.id != null) {
            updateSop(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.$store.dispatch("tagsView/delView", this.$route);
              // this.$router.replace('/qw/conversion/sop')
              window.location.replace('/qw/conversion/sop')
              this.reset();
            });
          } else {
            addSop(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.$store.dispatch("tagsView/delView", this.$route);
              // this.$router.replace('/qw/conversion/sop')
              window.location.replace('/qw/conversion/sop')
              this.reset();
            });
          }
        }
      });
    },

  }
};
</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>
