<template>
  <a @click="dialogTaskOpen" class="integral-create-task-btn">
    <el-dialog
      append-to-body
      :title="dialogTaskTitle"
      :visible.sync="dialogTaskVisible"
      width="600px"
      @close="formReset"
      :close-on-click-modal="false"
    >
      <el-form
        :model="taskForm"
        ref="newTaskForm"
        :rules="taskFormRules"
        @submit.native.prevent
        style="padding-right:20px;"
      >
        <el-form-item label="任务名称" prop="name" label-width="100px">
          <el-input
            maxlength="80"
            placeholder="请输入任务名称"
            type="textarea"
            :value="taskForm.name"
            v-model="taskForm.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="积分" prop="point" label-width="100px">
          <el-input-number style="width: 121px;" @change="getPoint" v-model="taskForm.point" :value="taskForm.point" :min="0" :max="10000"></el-input-number>
        </el-form-item>
        <el-form-item  label="按标准评分" label-width="100px" style="margin-bottom: 0px;">
         <div style="width: 43px;" @click="getMessage">
         <el-switch
            :disabled="iSplay"
            :value="isSwitch"
            v-model="isSwitch"
            @change="chngePoint"
          >
          </el-switch>
          </div>
        </el-form-item>
        <div style="color:#909399;font-size: 12px;padding-left: 98px;margin: 10px 0 18px 0;">任务可根据结果对应的标准评分</div>
        <div v-if="isSwitch">
        <el-form-item  label="评分标准" prop="point" label-width="100px" style="margin-bottom: 0px;">
          <div class="corde">
            <div class="cordeOne">
              <!-- <div class="bordeLine">{{oneCorde}}</div> -->
              <el-input type="number" v-model="oneCorde" :value="oneCorde"></el-input>
              <div>超预期</div>
            </div>
             <div class="cordeOne">
               <el-input type="number" v-model="twoCorde" :value="twoCorde"></el-input>
              <div>满意</div>
            </div>
             <div class="cordeOne">
             <el-input type="number"  @change="changeCorde" v-model="taskForm.point" :value="taskForm.point" ></el-input>
              <div>合格</div>
            </div>
             <div class="cordeOne">
               <el-input type="number" v-model="fourCorde" :value="fourCorde"></el-input>
              <div>不合格</div>
            </div>
          </div>
        </el-form-item>
        <div style="padding-left: 98px;color: #909399;font-size: 12px;margin-bottom: 4px;margin-top: 4px;">系统为您推荐了各标准的积分</div>
        <div style="padding-left: 98px;color: #909399;font-size: 12px;margin-bottom: 20px;">如需调整系统推荐的标准积分比例，<span style="color: #26A2FF;cursor: pointer;" @click="ChangeTask()">点击设置</span></div>
        </div>
         <el-form-item
          label="执行者"
          prop="performer"
          label-width="100px"
        >
          <el-select
            v-model="performer"
            filterable
            clearable
            placeholder="选择执行者"
            class="gap-right-8 first-element-btn"
            @change="ChosePerson"
          >
            <el-option
              v-for="item in employeeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

          <el-form-item
          label="任务类型"
          prop="performer"
          label-width="100px"
        >
          <el-select
            v-model="taskForm.task_type"
            filterable
            clearable
            placeholder="任务类型"
            class="gap-right-8 first-element-btn"

          >
            <el-option
              v-for="item in taskType"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item  label="开始时间"  prop="start_time" label-width="100px">
          <el-date-picker
            v-model="taskForm.start_time"
             type="datetime"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="截止时间" prop="expiretime" label-width="100px">
          <el-date-picker v-model="taskForm.expiretime"
                          type="datetime"
                          format="yyyy-MM-dd HH:mm:ss"
                          default-time="18:00:00"
                          placeholder="选择截止时间"></el-date-picker>
        </el-form-item>
        <div v-if="showAll" class="showAll" @click="changeShow()">显示全部...</div>
        <div v-else>
          <el-form-item  label="重复周期" prop="fixed_cycle" label-width="100px">
            <el-select
              v-model="taskForm.fixed_cycle"
              filterable
              clearable
              placeholder="选择重复周期"
              class="gap-right-8 first-element-btn"
            >
              <el-option
                v-for="item in fixed_cycle"
                :key="item.id"
                :label="item.type"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述" prop="remark" label-width="100px">
            <el-input
              maxlength="80"
              placeholder="输入任务描述"
              type="textarea"
              :value="taskForm.remark"
              v-model="taskForm.remark"
            ></el-input>
          </el-form-item>

          <el-form-item label="附件上传" label-width="100px">
            <upload_oss
              :headers="Xtoken"
              class="avatar-uploader"
              :action="'http://'+'integralsys.oss-cn-shenzhen.aliyuncs.com'"
              :show-file-list="true"
              :file-list="taskForm.file_list"
              :on-success="handleFilesSuccess"
              :on-preview="onFilePreView"
              :before-upload="beforeFilesUpload"
              :on-remove="onFileRemove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">仅支持上传图片</div>
            </upload_oss>

            <div style="display:none;">
              <img
                v-for="(item,index) in taskForm.file_list"
                :key="index"
                v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(item.name.split('.')[1]) >= 0"
                :src="item.response.url"
                :preview="index"
                :preview-text="item.name"
              >
            </div>
          </el-form-item>
          <el-form-item
            label="同时分配给"
            prop="follow"
            label-width="100px"
          >
            <el-select
              v-model="follow"
              multiple
              filterable
              clearable
              placeholder="选择分配者"
              class="gap-right-8 first-element-btn"
              @change="ender"
            >
              <el-option
                v-for="item in employeeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <!-- </el-scrollbar> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTaskClose('newTaskForm')">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="dialogTaskSend">确 定</el-button>
      </span>
    </el-dialog>
    <Scale  ref="loadingPlease":iShow="iShow"  @chngeShow="chngeShow"  />
    <div class="card-panel">
      <div class="tpzs6"></div>
      <div class="card-panel-description">
        <div class="card-panel-text">发布任务</div>
        <div class="card-panel-text2">自定义任务</div>
      </div>
    </div>
  </a>
</template>
<script>
  import Vue from 'vue'
  import qs from 'qs'
  import { getToken } from '@/utils/auth'
  import preview from '@/views/dashboard/components/preview/lib/index'
  import Scale from '@/views/dashboard/components/Scale'
  import 'vue-photo-preview/dist/skin.css'
  import upload_oss from '@/views/upload_oss/upload'

  Vue.use(preview, {
    tapToClose: false
  })
  export default {

    name: 'TaskCreateBtn',
     components: {
      Scale,
      upload_oss
    },
    data() {
      const taskFormRules = {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 2, max: 80, message: '长度在 2 到 80 个字符', trigger: 'blur' }
        ],
        expiretime: [
          { required: true, message: '请选择截止时间', trigger: 'blur' }
        ],
        // creator_id: [
        //   { required: true, message: '请选择执行人', trigger: 'blur'}
        // ],
        point: [
          { required: true, message: '请设置积分', trigger: 'blur'}
        ],
        fixed_cycle: [
          { required: true, message: '请选择重复周期', trigger: 'blur'}
        ]
      }
      // if (this.taskType == 2) {
      //   taskFormRules[follow_id] = [
      //     { required: true, message: "请选择负责人", trigger: "blur" }
      //   ];
      // }
      return {
        one: 0,
        two: 0,
        three: 0,
        four: 0,
        isSwitch: false,
        iSplay: true,
        iShow: false,
        showAll: true,  // 显示全部
        loading: false,
        fixed_cycle: [
          { id: 0, type: '从不' },
          { id: 1, type: '每天自动分配' },
          { id: 2, type: '每周自动分配' },
          { id: 3, type: '每月自动分配' }
        ],
        taskType: '1',
        profile: this.$store.getters.user_info,
        filter: {
          status: [],
          keywords: '',
          time_range: ''
        },
        Xtoken: { 'X-Token': getToken() },
        imageUrl: '',
        status_list: [
          { text: '未领取', value: 0 },
          { text: '已领取', value: 1 },
          { text: '已完成', value: 2 },
          { text: '已取消', value: -1 }
        ],
        dialogTaskVisible: false,
        dialogTaskTitle: '发布任务',
        totalCount: 0,
        currentPage: 1,
        pageLimit: 10,
        tableData: null,
        dialogCreateCategoryVisible: false,
        dialogEditCategoryVisible: false,
        // taskFormApi: '/integral.php/task/add',
        taskFormApi: '/integral.php/task/new_add',
        isRequest: false,
        employeeOptions: [],
        taskType:[
          {name: '普通任务', value: 10},
          {name:'关键任务', value: 20}
        ],
        taskForm: {
          task_type: 10,
          point_level_log: [],
          point_type: 10,
          name: '',  // 积分标题
          remark: '',  // 备注
          expiretime: '', // 过期时间
          point: 0,  // 奖分
          follow_id: [], // 执行者id+参与者id
          file_list: [],  // 附件
          fixed_cycle:  0,  // 重复周期
          // start_time:'', // 开始时间
          performer:[]
          // creator_id: '',  // 执行人id
        },
        performer: [], // 执行者id
        follow: [], // 参与者id
        taskFormRules: taskFormRules,
        accessEnabled: {
          add: 0,
          delete: 0,
          edit: 0
        },
        oneCorde: 0,
        twoCorde: 0,
        threeCorde: 0,
        fourCorde: 0,
      }
    },
    methods: {
      changeCorde() {
        console.log(this.threeCorde)
        //this.taskForm.point = this.threeCorde;
      },
      formReset() {
        this.iSplay = true;
        this.isSwitch = false;
        this.taskForm.point = 0;
        this.dialogTaskClose();
      },
       chngeShow() {
        console.log("jddj")
        this.iShow = false;
        this.getLevel();
        setTimeout(() => {
            this.getPoint();
      }, 200)

      },
      getPoint() {
        console.log("从家在")
        if(this.taskForm.point > 0) {
          this.iSplay = false;
       //  this.isSwitch = true;
        }else {
          this.iSplay = true;
          this.isSwitch = false;
        }
        console.log(this.one)
        console.log(this.two)
        console.log(this.three)
        console.log(this.four)
        this.oneCorde = Math.round((this.one/this.three)*this.taskForm.point);
        this.twoCorde = Math.round((this.two/this.three)*this.taskForm.point);
        this.threeCorde = this.taskForm.point;
        this.fourCorde = Math.round((this.four/this.three)*this.taskForm.point);
        console.log( (this.twoCorde ))
      },
      getMessage() {
        console.log("hhjhh")
        if(this.taskForm.point == 0) {
          this.$message({
            type: 'error',
            message: '请输入积分'
          })
        }
      },
      chngePoint() {
        console.log(this.isSwitch )
        if(this.taskForm.point > 0) {
          this.iSplay = false;

         // this.isSwitch = true;
        }else {
          this.iSplay = true;
         // this.isSwitch = false;
        }
      },
      ChangeTask() {
       // this.dialogTaskVisible = true;
        this.iShow = true;
       // this.$refs.loadingPlease.dialogTaskClose();
        this.$refs.loadingPlease.getCorde();
      },
      /// 设置选择执行者参与者不能重复选择
      ChosePerson(value) {

        const self = this;
        let array = [];
        array.push(value);
        if( self.follow.length !=0) {
          let chose = self.follow;
          let newArray = array.filter(i=>chose.indexOf(i) == -1)
          self.performer = newArray[0];
        }

      },
      ender(value) {
        const self = this;
        let choseArray = [];
        choseArray.push(self.performer)
        let array = [];
        array = value;
        if( self.performer.length !=0) {
          let newArray = array.filter(i=>choseArray.indexOf(i) == -1)
          self.follow = newArray;
        }

      },


      loadWidgetData: function() {
        var self = this
        const params = {
          id: this.profile.id,
          category_tree: 1,
          employee_list: 1
        }
        // 获取人员名单
        this.$http('get','/integral.php/ajax_request_common/prepare_integral_options',params)
          .then(function(response) {
            if (response.status == 200) {
              var jsonData = response.data
              try {
                self.employeeOptions = jsonData.employee_list
              } catch (err) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      onFilePreView(file) {
         window.open(file.response.url)
        return;
        // 点击时查看文件
        const $ext_list = ['doc', 'docx', 'pptx', 'xls', 'xlsx', 'ppt', 'txt']
        const $ext_name = file.name.split('.')[1]
        if ($ext_list.indexOf($ext_name) >= 0) {
          // console.log(
          //   'https://view.officeapps.live.com/op/view.aspx?src=' +
          //     this.serverdomain +
          //     file.url
          // )
          // window.open(
          //   'https://view.officeapps.live.com/op/view.aspx?src=' +
          //   this.serverdomain +
          //   file.response.url,
          //   '_blank'
          // )
        }
        // 点击时查看图片
        const $ext_list1 =  ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']
        const $ext_name1 = file.name.split('.')[1]
        if ($ext_list1.indexOf($ext_name1) >= 0) {
          // console.log(this.serverdomain + file.response.url)
          let ii = 0
          for (const i in this.taskForm.file_list) {
            if (
               ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG'].indexOf(
                this.taskForm.file_list[i].name.split('.')[1]
              ) >= 0
            ) {
              if (this.taskForm.file_list[i].name == file.name) {
                console.log(ii)
                this.openPhotoSwipe(
                  ii,
                  document.querySelectorAll('img[preview]')
                )

                return
              }
              ii++
            }
          }
        }
      },

      onFileRemove(file, fileList) {
        this.taskForm.file_list = fileList
      },

      handleFilesSuccess(response, file, fileList) {
        // this.taskForm.file_list = fileList
        this.$set(this.taskForm, 'file_list', fileList)
      },
      beforeFilesUpload(file) {
        const $ext_list = ['jpg', 'png', 'bmp', 'jpeg','PNG', 'JPG'];
        let len =  file.name.split('.').length - 1;
        const $ext_name = file.name.split('.')[len]
        if ($ext_list.indexOf($ext_name) != -1) {
          const isLt20M = file.size / 1024 / 1024 < 2
          if (!isLt20M) {
            this.$message.warning('您上图片不能大于2M')
            return false

          }
        }else {
          this.$message.warning('文件格式上传错误,仅支持上传图片）')
          return false
        }

      },

      dialogTaskClose: function() {
        const form = this.$refs['newTaskForm']
        this.$refs['newTaskForm'].resetFields();
        form.clearValidate();
        this.performer = [];
        this.follow = [];
        this.dialogTaskVisible = false;
        this.showAll = true;
        this.oneCorde = '';
        this.twoCorde = '';
        this.threeCorde = '';
        this.fourCorde = '';
        this.isSwitch = false;
      },

      dialogTaskOpen: function(id) {
        const self = this
        this.dialogTaskTitle = '发布任务'
        this.dialogTaskVisible = true
        // this.taskForm = {
        //   name: '',
        //   remark: '',
        //   expiretime: '',
        //   point: 0,
        //   follow_id: [],
        //   // creator_id:''

        // }
        this.$nextTick(() => {
          const form = this.$refs['newTaskForm']
          console.log(form)
          if (typeof id === 'undefined') {
            form.resetFields()
            form.clearValidate()
          }
        })
      },

      dialogTaskSend: function() {
          if(this.taskForm.point == 0) {
          this.$message({
            type: 'error',
            message: '积分不能为0'
          })
          return;
        }
        const self = this;
        let site_id = self.profile.site_id;  // 公司id
        console.log(site_id);
        let creator_id = self.profile.company_info.creator_id // 发布者id
        console.log(creator_id);
        this.taskForm.follow_id = this.follow.concat(self.performer);
        if (self.isRequest) {
          return
        }
        this.threeCorde = this.taskForm.point;
        console.log(this.isSwitch);
        if(this.isSwitch) {
          self.taskForm.point_type = 20;
          self.taskForm.point_level_log = [{key:40,value: this.fourCorde},{key:30,value:this.threeCorde},{key:20,value:this.twoCorde},{key:10,value:this.oneCorde}]
        }else {
          self.taskForm.point_type = 10;
          self.taskForm.point_level_log = [];
        }

        let newArray = [];
        for(var i = 0; i < self.taskForm.file_list.length; i ++) {
          if(self.taskForm.file_list[i].response != undefined ) {
            newArray.push({});
            newArray[i].name =  self.taskForm.file_list[i].name;
            newArray[i].response =  self.taskForm.file_list[i].response;
            delete newArray[i].response.extension;
            delete newArray[i].response.file_name;
            delete newArray[i].response.mime_type;
            delete newArray[i].response.path;
            delete newArray[i].response.status;
          }else {
            if(self.taskForm.file_list[i].status != undefined && self.taskForm.file_list[i].uid != undefined) {
              delete self.taskForm.file_list[i].status;
              delete self.taskForm.file_list[i].uid;
            }
            newArray.push(self.taskForm.file_list[i]);
          }
        }
        this.taskForm.file_list = newArray;
       if(self.taskForm.follow_id  =='' || self.taskForm.follow_id == undefined ) {
          delete self.taskForm.follow_id
        }
        const form = this.$refs['newTaskForm']
        form.validate(valid => {
          if (valid) {
            this.loading = true
            this.$http('post','/integral.php/task/new_add?site_id=' +`${site_id}` +'&creator_id=' + `${creator_id}`,qs.stringify({ row: this.taskForm}),
              // headers: {
              //   'Content-Type': 'application/x-www-form-urlencoded'
              // }
            )
              .then(function(response) {
                self.loading = false
                setTimeout(function() {
                  self.isRequest = false
                }, 200)

                var message = ''
                var status = 0
                if (response.status == 200) {
                  var data = response.data

                  message = data.msg
                  if (data.code == 1) {

                    self.dialogTaskClose()
                   // self.loadTaskList()
                    self.showAll = false;
                    self.performer = [];
                    self.follow = [];
                    self.oneCorde = 0
                    self.twoCorde = 0
                    self.threeCorde =0
                    self.fourCorde = 0
                    self.taskForm.point = 0
                    self.threeCorde = '';
                    self.isSwitch = false;
                    self.iSplay = true;
                     if(self.taskForm.follow_id  =='' || self.taskForm.follow_id == undefined ) {
                          self.$message({
                      // message: message,
                      dangerouslyUseHTMLString: true,
                      message: `<h3>${message}</h3>
                        <p>您可以在任务管理→任务大厅中查看</p>
                        `,
                          type: 'success'
                        })
                    }else {
                       self.$message({
                      // message: message,
                      dangerouslyUseHTMLString: true,
                      message: `<h3>${message}</h3>
                    <p>您可以在任务管理→我的任务→我发布的任务中查看</p>
                    `,
                      type: 'success'
                    })
                    }
                  } else {
                    self.$message({
                      message: message,
                      type: 'error'
                    })
                  }
                } else {
                  message = '服务器太忙了'
                }
              })
              .catch(function(error) {
                console.log(error)
              })
          } else {
            return false
          }
        })
      },

      dateTimeFormatter: function(row, column, cellValue) {
        return cellValue
          ? this.$moment(cellValue * 1000).format('YYYY-MM-DD HH:mm:ss')
          : ''
      },
      getLevel() {
        console.log("jdfjf");
        this.$http('get','/integral.php/taskscorelevel/getScoreLevel')
          .then(res => {
            if(res.data.code == 1000) {
            let { data = {} } = res.data;
            this.one = data.very_satisfied;
            console.log( this.one)
            this.two = data.satisfaction;
            this.three = data.qualified;
            this.four = data.failed;
          }
          })
      },
      // 点击展开余下弹窗
      changeShow() {
        this.showAll = false;


      },
    },
    created() {
      this.getLevel();
      this.loadWidgetData();
    }
  }
</script>
<style lang="scss" scoped>
  .integral-create-task-btn .tpzs6 {
    margin: 0 auto;
    width: 40px;
    height: 40px;
    background-image: url(static/images/fbrw.png);
    background-size: 100%;
  }
  .integral-create-task-btn .card-panel-description {
    width: 100%;
    text-align: center;
    color: #666;
  }
  .integral-create-task-btn .card-panel-text {
    line-height: 40px;
    font-size: 20px;
    font-weight: bold;
  }

  .integral-create-task-btn .card-panel-text2 {
    font-size: 14px;
    line-height: 20px;
    color: rgba(102, 102, 102, 1);
  }
  /* 表头样式设置 */
  .el-form-item__label {
    font-size: 14px;
    color:#606266;
    text-align: right;
    font-weight:normal;
  }
  .showAll {
    color: #26A2FF;
    padding-left: 33px;
    cursor: pointer;
  }
  /deep/ .el-dialog__header {
    padding: 30px 0 0 41px;
  }
  /deep/ .el-dialog__header .el-dialog__title{
    color: #303133;
    font-size: 17px;
    font-weight: 500;
  }
  /deep/ .el-form-item__label{
    font-weight: normal;
    padding-right: 20px;
  }
  /deep/ .el-dialog__body {
    padding-left: 92px;
  }

  /deep/ .el-textarea {
    width: 290px;
    height: 60px;
  }
  /deep/ .el-select {
    width: 223px;
  }
  .corde {
    display: flex;
    flex: 1;
    flex-direction: row;
  }
  .cordeOne {
    display: flex;
    flex-direction: column;
    width: 63px;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
  }
  .bordeLine {
    border: 1px solid #E4E7ED;
    width: 63px;
    height: 36px;
    text-align: center;
  }
.corde /deep/ .el-input__inner::-webkit-outer-spin-button,
.corde /deep/ .el-input__inner::-webkit-inner-spin-button {
   -webkit-appearance: none!important;
   appearance: none!important;
}
.el-dialog__close {
  display: none;
}

</style>

