<template>
  <div class="app-container">
    <div style="margin: 30px;" v-if="handleType==1"> 修改sop任务</div>
    <div style="margin: 30px;" v-if="handleType==2"> 查看sop任务
      <div style="float: right">
<!--        <el-button-->
<!--          type="primary"-->
<!--          @click="handleUpdateTags()"-->
<!--          v-hasPermi="['qw:sop:remove']"-->
<!--        >修改标签</el-button>-->
        <el-button
          type="primary"
          @click="handleUpdateQwUser()"
          v-hasPermi="['qw:sop:updateSopQwUser']"
        >修改员工</el-button>
        <el-button
          type="primary"
          @click="handleUpdateSopTemp()"
          v-hasPermi="['qw:sop:updateSopTemp']"
        >修改模板</el-button>
      </div>

      <el-divider></el-divider>
      <el-alert
        title="注意事项"
        type="warning"
        description="【持续生成记录中的状态】 的SOP任务仅能查看，不能修改（ps:可以在外面修改【过期时间】和【新客户自动创建sop】）"
        :closable="false"
        show-icon>
      </el-alert>
    </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="状态" prop="status">
            <dict-tag :options="statusOptions" :value="form.status"></dict-tag>
        </el-form-item>
<!--        <el-form-item label="状态">-->
<!--          <el-radio-group v-model="form.status">-->
<!--            <el-radio-->
<!--              v-for="dict in statusOptions"-->
<!--              :label="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>
        <el-form-item label="小转天数" prop="minConversionDay">
          <el-input class="el-input" v-model="form.minConversionDay" placeholder="请输入" style="width: 300px">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="大转天数" prop="maxConversionDay">
          <el-input class="el-input" v-model="form.maxConversionDay" placeholder="请输入" style="width: 300px">
            <template slot="append">天</template>
          </el-input>
        </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"
                :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>
          <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.toString()">
              </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 v-if="form.sendType==2 || form.sendType==4" label="自动添加SOP" prop="autoSopTime" >
          <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 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 label="模板" prop="tempId">
          <div @click="selectListSopTemp(form.sendType,0)" style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;">
            <el-tag type="success" style="margin: 3px;"
                    :disable-transitions="false"
                    v-for="list in tempList"
                    :key="list.id"
                    v-if="list.id === form.tempId">
              {{ form.tempName || list.name }}
            </el-tag>

            <!-- 如果 form.tempId 没有值，显示 '请选择模板' -->
            <span v-if="!form.tempId" style="margin: 3px; color: #999;">请选择模板</span>
          </div>
<!--          <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" style="float: right;" >
        <el-button v-if="handleType==1" type="primary" @click="submitForm">确 定</el-button>
        <el-button v-if="handleType==1" @click="cancel">取 消</el-button>

      </div>
      <el-dialog :custom-class="'fixed-dialog'" :title="listUser.title" :visible.sync="listUser.open" width="700px" append-to-body>
        <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
      </el-dialog>
      <el-dialog title="选择模板"  :visible.sync="tempOpen" append-to-body  >
        <sop-temp ref="SopTempComments" @sopTemp="sopTemp" @submitUpdateTemp="submitUpdateTemp"></sop-temp>
      </el-dialog>
      <!--  修改模板  -->
      <el-dialog :title="updateQwUserDialog.title" :visible.sync="updateQwUserDialog.open" width="500px" append-to-body>
        <el-form ref="form" :model="form" label-width="100px">
          <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>
        <div slot="footer" class="dialog-footer" >
          <el-button  type="primary" @click="submitUpdateQwUser">确 定</el-button>
          <el-button  @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

    </div>

  </div>
</template>

<script>
import { listSop, getSop, delSop, addSop, updateSop, exportSop,courseList,videoList,updateSopQwUser } from "@/api/qw/sop";
import { listSopTemp, getSopTemp, delSopTemp, addSopTemp, updateSopTemp, exportSopTemp } from "@/api/qw/sopTemp";
import { getQwAllUserList } 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 {sopListWxUserGroup} from "@/api/wxUser/wxUserGroup";
import source from "echarts/src/data/Source";
import SopTemp from "@/views/qw/sopTemp/sopTemp.vue";
// import { ElMessageBox } from 'element-plus';
export default {
  name: "updateSop",
  components: {SopTemp, CustomerGroupDetails, qwUserList,ImageUpload,sopLogsDetails},
  data() {
    return {
      updateQwUserDialog:{
        title:"修改成员",
        open:false
      },
      updateQwUserForm:{},
      handleType:null,
      //模板查询
      tempListLoading:false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      //模板遮罩
      tempOpen:false,
      // 选中数组
      ids: [],
      courseList:[],
      // videoList:[],
      tags:[],
      excludeTags:null,
      // 非单个禁用
      single: true,
      setting:[],
      tagList:[],
      tempList:[],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企微sop表格数据
      sopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      companyUserList:[],
      // 状态字典
      statusOptions: [],

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

      //个微客户的分组
      wxUserGroupList:[],

      sopLogsDialog:{
        title:'',
        open:false,
        sopLogsForm:[],
      },
      // 表单参数
      form: {
        status: 1,
        sendType:2,
        type: 2,
        filterType:2,
        autoSopTime:{},
      },
      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() {

    this.getDicts("sys_sop_status").then(response => {
      this.statusOptions = response.data;
      console.log(" this.statusOptions:"+ this.statusOptions)
    });


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

    const id = this.$route.params && this.$route.params.id;

    this.handleType = this.$route.params && this.$route.params.type;

    this.handleUpdate(id);

    //个微客户的分组
    sopListWxUserGroup().then(response => {
      this.wxUserGroupList = response.rows;
    });

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

  },
  watch:{
    userSelectList(newList) {
      this.form.qwUserIds = newList.map(item => item.id);
    }
  },
  methods: {
    submitUpdateQwUser(){
      this.form.qwUserIds = this.userSelectList.join(",");
      const data ={
        id:this.form.id,
        qwUserIds: this.form.qwUserIds
      }
      this.$confirm(
        '<span style="color: red; margin-bottom: 10px">是否确认修改当前任务员工?</span>' +
        '<span style="color: red;">(如有删除员工，对应的【营期也会删除】且【不可恢复】，请谨慎操作)</span>',
        "警告",
        {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true // 允许使用 HTML 字符串
      }).then(() => {
        this.updateQwUserDialog.open=false;
        return updateSopQwUser(data);
      }).then(response => {
        this.handleUpdate(data.id);
        this.msgSuccess("修改员工成功");
        this.updateQwUserDialog.open=false;
      }).catch(() => {
      });

    },
    handleUpdateTags(){

    },
    handleUpdateQwUser(){
      this.updateQwUserDialog.open = true
    },
    handleUpdateSopTemp(){
      this.selectListSopTemp(this.form.type,1)
    },
    //刷新部分数据
    refreshData(row){

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

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

    },

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

      this.tempOpen = true;
      setTimeout(() => {
        this.$refs.SopTempComments.getList(type,isUpdate);
      }, 200);

    },
    //确认修改模板
    submitUpdateTemp(val){
      console.log(val)
      const data = {
        tempId : val.id,
        tempName : val.name,
        id : this.form.id
      }
      this.$confirm('是否确认修改当前任务的模板为"' + data.tempName + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.tempOpen=false;
        return updateSop(data);
      }).then(response => {
        this.handleUpdate(data.id);
        this.msgSuccess("修改模板成功");
        this.tempOpen=false;
      }).catch(() => {
      });

    },

    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;

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

    },
    //选择变动时的变动
    handleSendTypeChange(val){
      this.tempList=[];
      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(id){
      // const index = this.userSelectList.findIndex(t => t === list);
      console.log(id)
      // if (index !== -1) {
      //   this.userSelectList.splice(index, 1);
      // }
      // 找到对应的员工信息
      const user = this.companyUserList.find((list) => list.id == id);
      console.log(user)
      if (!user) return;
      // 确认删除提醒
      this.$confirm('确定要删除员工"'+user.qwUserName+'"吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 用户点击确定
          const index = this.userSelectList.findIndex((t) => t === id);
          if (index !== -1) {
            this.userSelectList.splice(index, 1);
          }
          this.$message({
            type: 'success',
            message: '删除成功',
          });
        })
        .catch(() => {
          // 用户点击取消
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.replace('/qw/conversion/sop')
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getSop(row).then(response => {
        this.form = response.data;
        this.form.autoSopTime=JSON.parse(response.data.autoSopTime)
        this.open = true;
        this.userSelectList = this.form.qwUserIds.split(",");
        if (this.form.tags!==''&&this.form.tags!=null){
          this.tags = this.form.tags.split(",");
        }
        this.form.status = response.data.status.toString();
        if (this.form.excludeTags!==''&&this.form.excludeTags!=null){
          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.refreshData(this.form.corpId);

        this.title = "修改企微sop";
      });

    },

    // 表单重置
    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,
        autoSopTime:{},
      };
      this.resetForm("form");
      this.tags=[];
      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";
    },

    formatDateTo24HourString(date) {
      let year = date.getFullYear();
      let month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份需要加 1 并补零
      let day = ('0' + date.getDate()).slice(-2); // 日需要补零
      let hours = ('0' + date.getHours()).slice(-2); // 小时需要补零
      let minutes = ('0' + date.getMinutes()).slice(-2); // 分钟需要补零
      let seconds = ('0' + date.getSeconds()).slice(-2); // 秒需要补零

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    /** 提交按钮 */
    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.updateTime=this.formatDateTo24HourString(new Date());

          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;
}
/* 弹窗固定高度 */
.fixed-dialog {
  height: 500px; /* 固定高度 */
}

/* 内容区域滚动 */
.fixed-dialog .el-dialog__body {
  height: calc(100% - 110px); /* 减去标题和底部区域的高度 */
  overflow-y: auto; /* 垂直滚动 */
}
</style>
