<template>
  <div class="obpm-task">
    <div class="obpm-title">
      <div class="d-inline-block">
        <i class="el-icon-folder title-icon"></i>
        <div class="title-name d-inline-block ml-2">{{$t('task.title')}}</div>
      </div>
      <div class="bar d-inline-block float-right">
<!--        <el-button type="primary"  size="small" :disabled="start" @click="startTask" v-if="params.id!=''">{{$t('btns.start')}}</el-button>-->
<!--        <el-button type="danger"  size="small" :disabled="!start" @click="stopTask" v-if="params.id!=''">{{$t('btns.stopped')}}</el-button>-->
        <el-button type="primary" size="small" @click="btnSaveNew('params')" :loading="btnLoading">{{$t('btns.save_new')}}</el-button>
        <el-button type="primary" size="small" @click="btnSave('params')" :loading="btnLoading">{{$t('btns.save')}}</el-button>
        <el-button size="small" @click="goback">{{$t('btns.exit')}}</el-button>
      </div>
    </div>
    <el-scrollbar :style="{height: tableHeight + 'px'}" :native="false">
    <div class="mt-2">
      <el-form :model="params" ref="params" :rules="rules" label-position="top" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('task.name')" prop="name" class="padding0Label">
              <el-input v-model="params.name" size="small" class="width-360"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('task.creator')" class="padding0Label">
              <el-input readonly v-model="params.creator" size="small" class="width-360"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('task.type')" class="padding0Label">
            <el-select v-model="params.type" :placeholder="$t('placeholder.select')" size="small" class="width-360">
              <el-option :label="$t('menu.script')" value="1"></el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('task.startup_type')" class="padding0Label">
              <el-select v-model="params.startupType" :placeholder="$t('placeholder.select')" size="small" class="width-360">
                <el-option :label="$t('task.manual')" value="0"></el-option>
                <el-option :label="$t('task.auto')" value="1"></el-option>
                <el-option :label="$t('task.banned')" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('task.repeats')" class="padding0Label">
              <el-select :value="params.period" @change="onTimeChange" :placeholder="$t('placeholder.select')" size="small" style="width:200px;">
                <el-option :label="$t('task.do_not_repeat')" value="0"></el-option>
                <el-option :label="$t('task.immediately')" value="8192"></el-option>
                <el-option :label="$t('task.minute')" value="34"></el-option>
                <el-option :label="$t('task.hour')" value="546"></el-option>
                <el-option :label="$t('task.day')" value="2"></el-option>
                <el-option :label="$t('task.week')" value="32"></el-option>
                <el-option :label="$t('task.month')" value="512"></el-option>
              </el-select>
             <el-input  type="number"  v-model="params.interval" size="small"  placeholder="1" min="0" style="width:120px;margin-left:10px;"  v-if="params.period=='34'||params.period=='546'" @blur="checkInterval"></el-input>
             <span v-if="params.period=='34'">分钟</span>
             <span v-if="params.period=='546'">小时</span>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('task.modify_time')" class="padding0Label">
              <el-date-picker
                readonly
                v-model="params.modifyTime"
                type="date"
                class="width-360"
                format="yyyy-MM-dd HH:mm:ss"
                size="small"
                :placeholder="$t('placeholder.select_date')">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('task.description')" class="padding0Label">
              <el-input  type="textarea" :rows="2" v-model="params.description" size="small" class="width-360"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('task.terminate_condition')" class="padding0Label">
              <el-input  type="textarea" :rows="2" v-model="params.terminateScript" size="small" class="width-360"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('task.task_content')" class="padding0Label">
              <el-input type="textarea" :rows="2" v-model="params.taskScript" size="small" class="width-360" style="width: 95%"></el-input>
              <i class="el-icon-edit-outline" @click="showScriptEditor"></i>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="defaultVislble">
          <el-col :span="8">
            <el-form-item :label="$t('task.runtime')" prop="rDate" class="padding0Label">
              <el-date-picker
                v-model="params.rDate"
                type="date"
                size="small"
                class="width-360"
                :placeholder="$t('placeholder.select_date')"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('task.time')" prop="rTime" class="padding0Label">
              <el-time-picker 
                size="small"
                class="width-360"
                :placeholder="$t('placeholder.select_time')"
                v-model="params.rTime"
                value-format="HH:mm:ss"
                style="width: 100%;">
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="everyDayVisible">
          <el-col :span="8">
            <el-form-item :label="$t('task.time')" prop="rTime" class="padding0Label">
              <el-time-picker 
                size="small"
                class="width-360"
                :placeholder="$t('placeholder.select_time')"
                v-model="params.rTime"
                value-format="HH:mm:ss"
                style="width: 100%;">
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="weeklyVisible">
          <el-col :span="20">
            <el-form-item :label="$t('task.running_on')" class="padding0Label">
              <el-checkbox-group v-model="params.daysOfWeek">
                <el-checkbox label="1">{{$t('task.sunday')}}</el-checkbox>
                <el-checkbox label="2">{{$t('task.monday')}}</el-checkbox>
                <el-checkbox label="3">{{$t('task.tuesday')}}</el-checkbox>
                <el-checkbox label="4">{{$t('task.wednesday')}}</el-checkbox>
                <el-checkbox label="5">{{$t('task.thursday')}}</el-checkbox>
                <el-checkbox label="6">{{$t('task.friday')}}</el-checkbox>
                <el-checkbox label="7">{{$t('task.saturday')}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="weeklyVisible">
          <el-col :span="8">
            <el-form-item :label="$t('task.time')" prop="rTime" class="padding0Label">
              <el-time-picker 
                size="small"
                class="width-360"
                :placeholder="$t('placeholder.select_time')"
                v-model="params.rTime"
                value-format="HH:mm:ss"
                style="width: 100%;">
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="perMonthVisible">
          <el-col :span="8">
            <el-form-item :label="$t('placeholder.run_date')" class="padding0Label" size="small">
              <el-select v-model="params.dayOfMonth" :placeholder="$t('placeholder.select')" class="width-360">
                <el-option label="1" :value="1"></el-option>
                <el-option label="2" :value="2"></el-option>
                <el-option label="3" :value="3"></el-option>
                <el-option label="4" :value="4"></el-option>
                <el-option label="5" value="5"></el-option>
                <el-option label="6" :value="6"></el-option>
                <el-option label="7" :value="7"></el-option>
                <el-option label="8" :value="8"></el-option>
                <el-option label="9" :value="9"></el-option>
                <el-option label="10" :value="10"></el-option>
                <el-option label="11" :value="11"></el-option>
                <el-option label="12" :value="12"></el-option>
                <el-option label="13" :value="13"></el-option>
                <el-option label="14" :value="14"></el-option>
                <el-option label="15" :value="15"></el-option>
                <el-option label="16" :value="16"></el-option>
                <el-option label="17" :value="17"></el-option>
                <el-option label="18" :value="18"></el-option>
                <el-option label="19" :value="19"></el-option>
                <el-option label="20" :value="20"></el-option>
                <el-option label="21" :value="21"></el-option>
                <el-option label="22" :value="22"></el-option>
                <el-option label="23" :value="23"></el-option>
                <el-option label="24" :value="24"></el-option>
                <el-option label="25" :value="25"></el-option>
                <el-option label="26" :value="26"></el-option>
                <el-option label="27" :value="27"></el-option>
                <el-option label="28" :value="28"></el-option>
                <el-option label="29" :value="29"></el-option>
                <el-option label="30" :value="30"></el-option>
                <el-option label="31" :value="31"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('task.time')" prop="rTime" class="padding0Label">
              <el-time-picker 
                size="small"
                class="width-360"
                :placeholder="$t('placeholder.select_time')"
                v-model="params.rTime"
                value-format="HH:mm:ss"
                style="width: 100%;">
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    </el-scrollbar>

    <!-- 脚本选择器弹窗 -->
    <!-- scriptEditorVisible:弹窗显示   showScritptEditorCode：将文本框的值传给编译器  handleScriptEditor：将编译器的值传给textarea-->
    <ScriptEditorSelect
      v-if="scriptEditorVisible"
      :scriptEditorVisible="scriptEditorVisible"
      :editorCode="showScritptEditorCode"
      @closeScriptEditorDialog="scriptEditorVisible = false"
      @saveScriptEditor="handleScriptEditor"
    />
  </div>
</template>
<script>
import { createTasks, updateTasks, startTask, stopTask } from "@/service/CommontoolsAPI.js";
import { getSuperuser } from "@/service/CommonApi.js";
import { TimeToDate,nameCheck} from "@/utils/utils.js";
import ScriptEditorSelect from "@/components/Common/scriptEditor";

export default {
  name: 'task',
  components:{
    ScriptEditorSelect
  },
  data(){
    return{
      user: {},
      params: {
        appId: "",
        id: "",
        name: "",                 //任务名称
        creatorid: "",            //创建人id
        creator: "",              //创建人
        type: "1",                 //类型
        startupType: "0",          //启动类型
        period: "0",               //周期
        interval:'1',
        modifyTime: "",           //修改时间
        description: "",          //描述
        terminateScript: "",      //终止脚本
        taskScript: "",           //任务脚本
        rDate: "",                //运行时间
        rTime: "",                //时间
        daysOfWeek: [],           //运行一周，周日、周一...
        dayOfMonth: 1             //运行日期，1~31  
      },
      rules: {
        name: [
          { required: true, message: this.$t('placeholder.name'), trigger: 'blur' },
          { validator: nameCheck, trigger: "blur" },
        ],
        rDate: [
          { required: true, message: this.$t('placeholder.select_date'), trigger: 'change' }
        ],
        rTime: [
          { required: true, message: this.$t('placeholder.select_time'), trigger: 'change' }
        ],
      },
      defaultVislble: true,     //默认，不重复
      theDayVislble: false,     //立刻、分钟、小时
      everyDayVisible: false,   //每日
      weeklyVisible: false,     //每周
      perMonthVisible: false,   //每月
      start: false,
      tableHeight: 400,
      scriptEditorVisible: false, // 脚本编辑器弹窗
      btnLoading: false, // 请求资源是按钮loading
    }
  },

  mounted(){
    //获取特权用户
    this.getSuperuser();
    //获取当前时间
    this.initDate();
    if(this.$route.query.edit == true || this.$route.query.edit == 'true'){
      let record = this.$route.query.params;
      let defaultVislble = false;
      let theDayVislble = false;
      let everyDayVisible = false;
      let weeklyVisible = false;
      let perMonthVisible = false;
      switch(record.period){
        case 0:
          defaultVislble =  true;
          break;
        case 8192:
          theDayVislble =  true;
          break;
        case 34:
          theDayVislble =  true;
          break;
        case 546:
          theDayVislble =  true;
          break;
        case 2:
          everyDayVisible =  true;
          break;
        case 32:
          weeklyVisible =  true;
          break;
        case 512:
          perMonthVisible =  true;
          break;
      }
      let params = {
        ...this.params,
        appId: record.appId,
        id:  record.id,
        name:  record.name,                 //任务名称
        creatorid:  record.creatorid,            //创建人id
        creator:  record.creator,              //创建人
        type: String(record.type),                 //类型
        startupType: String(record.startupType),          //启动类型
        period: String(record.period),               //周期
        interval:String(record.interval),
        modifyTime: record.modifyTime,           //修改时间
        description: record.description,          //描述
        terminateScript: record.terminateScript,      //终止脚本
        taskScript: record.taskScript,           //任务脚本
        rDate: record.rDate,                //运行时间
        rTime: record.rTime,            //时间
        daysOfWeek: record.daysOfWeek ? record.daysOfWeek : [] ,
        dayOfMonth: record.dayOfMonth ? record.dayOfMonth : 1,
      }
      this.params = params;
      this.defaultVislble =  defaultVislble;
      this.theDayVislble = theDayVislble;
      this.everyDayVisible =  everyDayVisible;
      this.weeklyVisible = weeklyVisible;
      this.perMonthVisible = perMonthVisible;
    }else{
      let appId = sessionStorage.getItem("appId");
      let params = {
        ...this.params,
        appId: appId,
      }
      this.params = params;
    }
    this.getScollerHeight();
  },

  methods:{
    /**
     * 动态计算页面table高度
     */
    getScollerHeight() {
      setTimeout(() => {
        let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        //60 头部， 32 面包屑， 41 第一层页签， 40 第二层页签， 50 列表标题， 71 查询， 20 父组件外边距, 40分页
        this.tableHeight = clientHeight - 60 - 32 - 41 - 40 - 50 - 20
      }, 100)
    },

    /**
     * **获取特权用户信息**
     */
    getSuperuser(){
      getSuperuser({
        onSucess: response => {
          if (response.data.errcode == 0) {
            this.user = response.data.data;
            this.params.creatorid = response.data.data.id;            
            this.params.creator = response.data.data.name;
          }
        }
      })
    },

    /**
     * 获取当前时间
     */
    initDate(){
      let time = new Date();
      let date = TimeToDate(time, "YYYY-MM-DD h:m:s");
      this.params.modifyTime = date;
    },
    //修改interval
  checkInterval(){
    if(this.params.period=='34'){
      if(this.params.interval>60||this.params.interval<0) {
        alert('应该输入0-60的合理数据')
        this.params.interval=1
      }
    }else {
      if(this.params.interval<0||this.params.interval>3600){
        alert('应该输入0-3600的合理数据')
        this.params.interval=1
      }
    }
  },
    /**
     * 退出
     */
    goback(){
      this.$router.push({path: '/home/softwaresdetails/commontool/tasklist', query:{edit: true}});
    },

    /**
     * 切换重复-时间
     */
    onTimeChange(e){
      let defaultVislble = false;
      let theDayVislble = false;
      let everyDayVisible = false;
      let weeklyVisible = false;
      let perMonthVisible = false;
      switch(Number(e)){
        case 0:
          defaultVislble =  true;
          break;
        case 8192:
          theDayVislble =  true;
          break;
        case 34:
          theDayVislble =  true;
          break;
        case 546:
          theDayVislble =  true;
          break;
        case 2:
          everyDayVisible =  true;
          break;
        case 32:
          weeklyVisible =  true;
          break;
        case 512:
          perMonthVisible =  true;
          break;
      }
      let params = {
        ...this.params,
        period: e,  
      }
      this.params = params;
      this.defaultVislble =  defaultVislble;
      this.theDayVislble = theDayVislble;
      this.everyDayVisible =  everyDayVisible;
      this.weeklyVisible = weeklyVisible;
      this.perMonthVisible = perMonthVisible;
    },

    /**
     * 保存操作
     */
    btnSave(formName, type){
      this.initDate()
      let params = {
        ...this.params,
        type: Number(this.params.type),
        startupType: Number(this.params.startupType),
        period: Number(this.params.period),
        interval:Number(this.params.interval)&&(this.params.period=='34'||this.params.period=='546')?Number(this.params.interval):1,
        dayOfMonth: Number(this.params.dayOfMonth),
      }
      if(this.params.id != ""){
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            //更新
            this.btnLoading = true
            let response = await updateTasks(params);
            this.btnLoading = false
            if (response.data.errcode == 0) {
              this.$message.success(this.$t('msg.ss'));
              if(type=='save_new'){
                this.resetFields();
              }
            }
          } else {
            return false;
          }
        });
      }else{
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            //创建
            this.btnLoading = true
            let response = await createTasks(params);
            this.btnLoading = false
            if (response.data.errcode == 0) {
              let data = {
                ...this.params,
                id: response.data.data.id
              };
              this.params = data;
              this.$message.success(this.$t('msg.ss'));
              if(type=='save_new'){
                this.resetFields();
              }
            }
          } else {
            return false;
          }
        });
      }
    },

    /**
     * 保存并新建
     */
    btnSaveNew(params){
      this.btnSave(params, 'save_new')
    },

    /**
     * 重置内容
     */
    resetFields(){
      this.params = {
        appId: sessionStorage.getItem("appId"),
        id: "",
        name: "",                 //任务名称
        creatorid: "",            //创建人id
        creator: "",              //创建人
        type: "1",                 //类型
        startupType: "0",          //启动类型
        period: "0",               //周期
        interval:'1',
        modifyTime: "",           //修改时间
        description: "",          //描述
        terminateScript: "",      //终止脚本
        taskScript: "",           //任务脚本
        rDate: "",                //运行时间
        rTime: "",                //时间
        daysOfWeek: [],           //运行一周，周日、周一...
        dayOfMonth: 1             //运行日期，1~31  
      }
      // 清空校验
      this.$refs['params'].resetFields()
    },

    /**
     * 开始任务
     */
    startTask(){
      startTask(this.params, {
        onSucess: response => {
          if (response.data.errcode == 0) {
            this.$message({
              message: response.data.data.msg,
              type: 'success'
            });
            this.start = true;
          }
        }
      })
    },

    /**
     * 停止任务
     */
    stopTask(){
      stopTask(this.params, {
        onSucess: response => {
          if (response.data.errcode == 0) {
            this.$message({
              message: response.data.data.msg,
              type: 'success'
            });
            this.start = false;
          }
        }
      })
    },

    /**
     * 显示脚本编辑器弹框
     */
    showScriptEditor () {
      this.scriptEditorVisible = true;
    },
    /**
     * 将脚本编辑器的值写入到textarea中
     */
    handleScriptEditor (val) {
      this.params.taskScript = val
    },
  },
  computed:{
    /**
     * textarea 传给 脚本编辑器的值
     */
    showScritptEditorCode () {
      return this.params.taskScript
    },
  },
}
</script>