<template>
  <div style=" background-color: #fff; padding:15px;">
    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
      <el-button
        class="first-element-btn"
        v-if="profile.manager_type > 1"
        :disabled="multipleSelection.length < 1"
        @click="confirmMultipleDelete"
        type="primary"
        plain
      >批量删除</el-button>
      <el-cascader
        clearable
        :options="categoryTree"
        change-on-select
        v-model="filter.category_id"
        @change="onFilterChanged"
        placeholder="选择分类进行筛选或编辑"
        class="gap-right-8 first-element-btn"
      ></el-cascader>



      <div class="gap-right-8" style="display:inline-block; width:220px;">
        <el-input
          placeholder="输入关键词查找"
          ref="search-bar"
          v-model="filter.keywords"
          class="input-with-select"
          @keyup.enter.native="onFilterChanged"
        >
          <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
        </el-input>
      </div>
      <el-button
        @click="dialogCreateCategoryVisible = true"
        v-show="accessEnabled.add == 1"
        type="primary"
        plain
      >新增分类</el-button>

      <el-button
        @click="dialogCategoryListVisible = true"
        type="primary"
        plain
        v-show="accessEnabled.add == 1"
      >分类管理</el-button>

      <el-button
        @click="dialogTaskOpen"
        v-show="accessEnabled.add == 1"
        type="primary"
        plain
      >新增工作</el-button>

      <el-button
        @click="dialogExcelVisible = true"
        v-show="accessEnabled.excel_import == 1 && false"
        type="primary"
        plain
      >Excel管理</el-button>
    </div>
    <el-table
      v-loading="loading"
      ref="multipleTable"
      @filter-change="filterHandler"
      @selection-change="handleSelectionChange"
      :data="tableData"
      :border="false"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        width="42"
        v-if="profile.manager_type > 1"
        :selectable="selectable"
      ></el-table-column>
      <!-- <el-table-column prop="category_name" label="积分分类" :filterMultiple="false" column-key="category" :filters="status_list"> -->
      <el-table-column prop="category_name" label="分类" :filterMultiple="false"></el-table-column>
      <el-table-column prop="name" label="任务名称"></el-table-column>
      <!-- <el-table-column prop="items" label="细则内容" :show-overflow-tooltip="true"> -->
      <el-table-column label="备注">
        <template slot-scope="scope">
{{scope.row.remark}}
        </template>
      </el-table-column>
      <el-table-column
        prop="point"
        label="积分"
      ></el-table-column>

      <el-table-column label="分发周期">
        <template slot-scope="scope">
          <span v-if="scope.row.cycle_type == 0">每天</span>
          <span v-if="scope.row.cycle_type == 1">每周</span>
          <span v-if="scope.row.cycle_type == 2">每月</span>
        </template>
      </el-table-column>

      <el-table-column label="分发时间">
        <template slot-scope="scope">
          <span v-if="scope.row.cycle_type == 0">{{scope.row.distribution_time}}:00</span>
          <span v-if="scope.row.cycle_type == 1">
            <span v-if="scope.row.distribution_date==1">星期一 </span>
            <span v-if="scope.row.distribution_date==2">星期二 </span>
            <span v-if="scope.row.distribution_date==3">星期三 </span>
            <span v-if="scope.row.distribution_date==4">星期四 </span>
            <span v-if="scope.row.distribution_date==5">星期五 </span>
            <span v-if="scope.row.distribution_date==6">星期六 </span>
            <span v-if="scope.row.distribution_date==7">星期日 </span>{{scope.row.distribution_time}}:00
          </span>
          <span v-if="scope.row.cycle_type == 2">第{{scope.row.distribution_date}}天 {{scope.row.distribution_time}}:00</span>
        </template>
      </el-table-column>


      <el-table-column label="操作">
        <template slot-scope="scope">
          <span v-if="profile.manager_type > 1">
            <el-button
              type="text"
              v-if="multipleSelection.length < 1"
              @click="dialogTaskOpen('修改任务', scope.row.id)"
              :disabled="accessEnabled.edit != 1"
            >修改</el-button>
            <el-button
              style="margin-left:0;"
              type="text"
              @click="confirmDelete(scope.row.id)"
              :disabled="accessEnabled.delete != 1"
              v-bind:title="accessEnabled.delete != 1 ? '没有删除权限' : ''"
            >删除</el-button>
          </span>
          <!-- <div v-else> -->
          <el-button style="display:none;" type="text" @click="loadRuleDetail(scope.row.id)">查看</el-button>
          <!-- </div> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="total,sizes, prev, pager, next"
      :page-size="pageLimit"
      :page-sizes="[10, 20, 50, 100]"
      :total="totalCount"
      @size-change="handleSizeChange"
      :current-page.sync="currentPage"
      @current-change="changePage"
    ></el-pagination>
    <el-dialog
      title="新增分类"
      width="600px"
      :visible.sync="dialogCreateCategoryVisible"
      :close-on-click-modal="false"
      @close="onDismissCreateCategoryDialog"
    >
      <el-form
        ref="newCategoryForm"
        :model="newCategoryForm"
        :rules="rules"
        @submit.native.prevent
        style="padding-right:20px;"
      >
        <el-form-item label="分类名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="newCategoryForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="从属分类" prop="pid" :label-width="formLabelWidth">
          <el-cascader
            v-model="newCategoryForm.pid"
            clearable
            :options="categoryTree"
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateCategoryVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCreateCategoryForm('newCategoryForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="任务分类管理"
      width="800px"
      :visible.sync="dialogCategoryListVisible"
      :close-on-click-modal="false"
      @open="category_manage_open"
    >
      <TaskCategoryManage ref="rule_category_manage_com"></TaskCategoryManage>
    </el-dialog>
    <el-dialog
      title="编辑分类"
      width="600px"
      :visible.sync="dialogEditCategoryVisible"
      :close-on-click-modal="false"
      @close="onDismissEditCategoryDialog"
    >
      <el-form
        ref="categoryForm"
        :model="categoryForm"
        :rules="rules"
        @submit.native.prevent
        style="padding-right:20px;"
      >
        <el-form-item label="分类名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="categoryForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="从属分类" prop="pid" :label-width="formLabelWidth">
          <el-cascader
            v-model="categoryForm.pid"
            clearable
            :options="parentCategoryTree"
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="deleteCategory()" v-show="accessEnabled.delete == 1">删除此分类</el-button>
        <el-button @click="dialogEditCategoryVisible = false">取 消</el-button>
        <el-button type="text" @click="submitEditCategoryForm('categoryForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="积分规则"
      width="650px"
      :visible.sync="dialogRuleVisible"
      :close-on-click-modal="false"
      @close="clearRuleForm"
    >
      <el-form ref="ruleForm" :model="ruleForm" style="padding-right:20px;">
        <el-form-item label="积分分类" :label-width="formLabelWidth">
          <span>{{ ruleForm.category_path }}</span>
        </el-form-item>
        <el-form-item label="积分规则" :label-width="formLabelWidth">
          <span>{{ ruleForm.name }}</span>
        </el-form-item>
        <el-form-item label="积分细则" :label-width="formLabelWidth">
          <!-- <ul style="margin-left: 25px;"> -->
          <div v-for="item in ruleForm.items" :key="item.id">
            <div>{{ item.content + ' ' + generatePointIndication(item) }}</div>
            <div>{{ item.remark }}</div>
          </div>
          <!-- </ul> -->
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <span>{{ ruleForm.remark }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      width="600px"
      title="Excel管理"
      :visible.sync="dialogExcelVisible"
      :close-on-click-modal="false"
    >
      <div style="padding:0 50px;">
        <div class="align-center" style="margin-bottom:20px;">
          <p>温馨提示：</p>
          <p>1、导入之前请点击“下载模板”按钮下载模板文件；</p>
          <p>2、填写规则到Excel电子表中；</p>
          <p>3、点击“Excel文件导入”上传填写好的电子表；</p>
          <p>4、支持上传大小500KB以内的Excel文件。</p>
          <p>5、导入之前请先建立好规则分类。</p>
          <p></p>
        </div>

        <div class="align-center" style="margin-bottom:20px; float:left; margin-left:10px;">
          <el-button type="primary" @click="downloadTemplate" plain>下载模板</el-button>
        </div>
        <div class="align-center" style="margin-bottom:20px; float:left; margin-left:10px;">
          <el-upload
            action="/integral.php/excel_util/test_link"
            :show-file-list="false"
            :http-request="uploadFile"
            v-show="accessEnabled.excel_import == 1"
          >
            <el-button type="primary">Excel导入</el-button>
          </el-upload>
        </div>
        <div class="align-center" style="margin-bottom:20px; float:left;margin-left:10px;">
          <el-button type="primary" @click="downloadSheet">Excel导出</el-button>
        </div>

        <div style="clear:both;"></div>
      </div>
    </el-dialog>

    <el-dialog
      class="ruleEditBox"
      title="规则"
      @close="formReset"
      :visible.sync="RuleDetailDialogVisible"
      :close-on-click-modal="false"
      width="700px"
      top="50px"
    >
      <RuleDetail ref="RuleDetailView"></RuleDetail>
    </el-dialog>



    <el-dialog
      :title="dialogTaskTitle"
      :visible.sync="dialogTaskVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="taskForm" ref="newTaskForm" :rules="taskFormRules" @submit.native.prevent>
        <!-- <el-tabs v-model="activeName">
       <el-tab-pane label="任务信息" name="first"> -->
         <div style="padding:30px 50px;">

           <el-form-item label="任务名称" prop="name" label-width="100px">
             <el-input v-model="taskForm.name" :value="taskForm.name" auto-complete="off"></el-input>
           </el-form-item>

           <el-form-item label="奖励积分" prop="point" label-width="100px">
             <el-input-number
               v-model="taskForm.point"
               :value="taskForm.point"
               :min="1"
               :max="10000"
             ></el-input-number>

             <el-button type="text" @click="set_point_config" style="margin-left:20px;">高级设置 <span v-show="point_config_show == false">∨</span><span v-show="point_config_show == true">∧</span></el-button>
             <el-row :gutter="5" v-if="point_config_show">
               <el-col v-for="(item,index) in taskForm.point_config" :key="index" :span="6"><p style="line-height: 1.5; margin-bottom: 0;">{{item.label}}</p>
               <el-input type="number" v-model="item.point"></el-input>
               </el-col>
             </el-row>
           </el-form-item>
           <el-form-item label="分发周期" prop label-width="100px">
             <el-select v-model="taskForm.cycle_type">
               <el-option :value="0" label="每天">每天</el-option>
               <el-option :value="1" label="每周">每周</el-option>
               <el-option :value="2" label="每月">每月</el-option>
             </el-select>
           </el-form-item>
           <el-form-item v-show="taskType == 1" label="分发时间" label-width="100px">


             <el-select v-model="taskForm.distribution_date"  v-if="taskForm.cycle_type == 2" style="width:140px;">
               <el-option :value="1" label="第1天">第1天</el-option>
               <el-option :value="2" label="第2天">第2天</el-option>
               <el-option :value="3" label="第3天">第3天</el-option>
               <el-option :value="4" label="第4天">第4天</el-option>
               <el-option :value="5" label="第5天">第5天</el-option>
               <el-option :value="6" label="第6天">第6天</el-option>
               <el-option :value="7" label="第7天">第7天</el-option>
               <el-option :value="8" label="第8天">第8天</el-option>
               <el-option :value="9" label="第9天">第9天</el-option>
               <el-option :value="10" label="第10天">第10天</el-option>
               <el-option :value="11" label="第11天">第11天</el-option>
               <el-option :value="12" label="第12天">第12天</el-option>
               <el-option :value="13" label="第13天">第13天</el-option>
               <el-option :value="14" label="第14天">第14天</el-option>
               <el-option :value="15" label="第15天">第15天</el-option>
               <el-option :value="16" label="第16天">第16天</el-option>
               <el-option :value="17" label="第17天">第17天</el-option>
               <el-option :value="18" label="第18天">第18天</el-option>
               <el-option :value="19" label="第19天">第19天</el-option>
               <el-option :value="20" label="第20天">第20天</el-option>
               <el-option :value="21" label="第21天">第21天</el-option>
               <el-option :value="22" label="第22天">第22天</el-option>
               <el-option :value="23" label="第23天">第23天</el-option>
               <el-option :value="24" label="第24天">第24天</el-option>
               <el-option :value="25" label="第25天">第25天</el-option>
               <el-option :value="26" label="第26天">第26天</el-option>
               <el-option :value="27" label="第27天">第27天</el-option>
               <el-option :value="28" label="第28天">第28天</el-option>
               <el-option :value="29" label="第29天">第29天</el-option>
               <el-option :value="30" label="第30天">第30天</el-option>
               <el-option :value="31" label="第31天">第31天</el-option>
             </el-select>
             <el-select v-model="taskForm.distribution_date" v-if="taskForm.cycle_type == 1" style="width:140px;">
               <el-option :value="1" label="星期一">星期一</el-option>
               <el-option :value="2" label="星期二">星期二</el-option>
               <el-option :value="3" label="星期三">星期三</el-option>
               <el-option :value="4" label="星期四">星期四</el-option>
               <el-option :value="5" label="星期五">星期五</el-option>
               <el-option :value="6" label="星期六">星期六</el-option>
               <el-option :value="7" label="星期日">星期日</el-option>
             </el-select>

             <el-select v-model="taskForm.distribution_time" style="width:140px;">
               <el-option :value="0" label="00:00">00:00</el-option>
               <el-option :value="1" label="01:00">01:00</el-option>
               <el-option :value="2" label="02:00">02:00</el-option>
               <el-option :value="3" label="03:00">03:00</el-option>
               <el-option :value="4" label="04:00">04:00</el-option>
               <el-option :value="5" label="05:00">05:00</el-option>
               <el-option :value="6" label="06:00">06:00</el-option>
               <el-option :value="7" label="07:00">07:00</el-option>
               <el-option :value="8" label="08:00">08:00</el-option>
               <el-option :value="9" label="09:00">09:00</el-option>
               <el-option :value="10" label="10:00">10:00</el-option>
               <el-option :value="11" label="11:00">11:00</el-option>
               <el-option :value="12" label="12:00">12:00</el-option>
               <el-option :value="13" label="13:00">13:00</el-option>
               <el-option :value="14" label="14:00">14:00</el-option>
               <el-option :value="15" label="15:00">15:00</el-option>
               <el-option :value="16" label="16:00">16:00</el-option>
               <el-option :value="17" label="17:00">17:00</el-option>
               <el-option :value="18" label="18:00">18:00</el-option>
               <el-option :value="19" label="19:00">19:00</el-option>
               <el-option :value="20" label="20:00">20:00</el-option>
               <el-option :value="21" label="21:00">21:00</el-option>
               <el-option :value="22" label="22:00">22:00</el-option>
               <el-option :value="23" label="23:00">23:00</el-option>
             </el-select>


           </el-form-item>

           <el-form-item label="所属分类" prop="pid" label-width="100px">
             <el-cascader
               v-model="taskForm.category_id"
               clearable
               :options="categoryTree"
               change-on-select
             ></el-cascader>
           </el-form-item>



           <el-form-item label="任务说明" prop="remark" label-width="100px">
             <el-input placeholder="任务说明（最多100字）" maxlength="100" type="textarea" :value="taskForm.remark" v-model="taskForm.remark"></el-input>
           </el-form-item>
         </div>
       <!--</el-tab-pane>
       <el-tab-pane label="附件" name="second" v-if="false">-->
            <el-scrollbar v-if="false"
              wrap-class="column-wrapper scrollable-items-container"
              :native="false"
              style="height: 300px;"
            >
              <div style="padding:30px 50px;">
                <el-form-item>
                  <el-alert
                    title="温馨提示："
                    type="success"
                    description="" style="margin-bottom:15px;">
                    <p style="margin: 0" class="diy-tip">1、可上传图片（jpg, png, bmp, jpeg）格式</p>
                    <p style="margin: 0" class="diy-tip">2、可上传文件（doc, docx, pptx, xls, xlsx, ppt, txt, pdf）格式</p>
                  </el-alert>

                  <upload_oss
                    :headers="Xtoken"
                    class="avatar-uploader"
                    :action="serverdomain+'/integral.php/upload'"
                    :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>
                    <!-- <p>可上传图片(jpg, png, bmp, jpeg)以及文件(doc, docx, pptx, xls, xlsx, ppt, txt)</p> -->
                  </upload_oss>
                  
                  <!-- <el-upload
                    :headers="Xtoken"
                    class="avatar-uploader"
                    :action="serverdomain+'/integral.php/upload'"
                    :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>
                  </el-upload> -->

                  <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="serverdomain+item.response.url"
                      :preview="item.uid"
                      :preview-text="item.name"
                    >
                  </div>
                </el-form-item>
              </div>
            </el-scrollbar>
            <!--</el-tab-pane>
      </el-tabs>-->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogTaskClose">取 消</el-button>
      <el-button type="primary" :loading="sendloading" @click="dialogTaskSend">确 定</el-button>
    </span>
  </el-dialog>



</div>
</template>
<script>
import TaskCategoryManage from '@/views/performance/TaskCategoryManage'
import RuleDetail from '@/views/integral/RuleDetail'
import Vue from 'vue'
import qs from 'qs'
import { getToken } from '@/utils/auth'
import preview from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'
import upload_oss from '@/views/upload_oss/upload'

Vue.use(preview, {
  tapToClose: false
})
export default {
  components: {
    TaskCategoryManage,
    RuleDetail,
    upload_oss
  },

  data() {
    const taskFormRules = {
      name: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
      ],
      expiretime: [
        { required: true, message: '请选择截止时间', trigger: 'change' },
        { min: 11, max: 50, message: '请选择截止时间', trigger: 'blur' }
      ]
    }
    const validateName = (rule, value, callback) => {
      var validValue = value
        ? value.replace(/\s/g, '').replace(/&nbsp;/gi, '')
        : value
      if (!validValue) {
        return callback(new Error('请填写积分分类名称'))
      } else {
        callback()
      }
    }
    return {
      point_config_show: false,
      profile: this.$store.getters.user_info,
      expiredate:'',
      expiretime:'',
      fixed_cycle: [
        { id: 1, type: '每天自动分配' },
        { id: 2, type: '每周自动分配' },
        { id: 3, type: '每月自动分配' }
      ],
      taskType: '1',
      activeName: 'first',
      Xtoken: { 'X-Token': getToken() },
      files: [],
      activeName: 'first',
      dialogTaskVisible: false,
      dialogTaskTitle: '新增绩效工作',
      taskFormApi: '/integral.php/performance_work/common_task_add',
      multipleSelection: [],
      textTip: '选择积分分类筛选',
      show3: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      RuleDetailDialogVisible: false,
      RuleDetailDialogTitle: '增加规则',

      status_list: [],

      pageLimit: 10,
      outerVisible: false,
      innerVisible: false,

      profile: this.$store.getters.user_info,
      filter: {
        dept_id: [],
        status: 1,
        keywords: '',
        category_id: null
      },
      sendloading: false,
      loading: false,
      totalCount: 0,
      currentPage: 1,
      tableData: null,
      dialogCategoryListVisible: false,
      dialogCreateCategoryVisible: false,
      dialogEditCategoryVisible: false,
      dialogRuleVisible: false,
      dialogExcelVisible: false,
      newCategoryForm: {
        name: '',
        pid: []
      },
      pointTypes: [],
      categoryForm: {
        id: '',
        name: '',
        pid: []
      },
      ruleForm: {},
      categoryTree: [],
      parentCategoryTree: [],
      formLabelWidth: '105px',
      rules: {
        name: [{ validator: validateName, trigger: 'blur' }]
      },

      taskForm: {
        set_point_config:1,
        cycle_type: 0,
        name: '',
        remark: '',
        task_time: '',
        category_id:[],
        distribution_date:1,
        distribution_time:8,
        point: 0,
        file_list: [],
        point_config: [
          {
            label:'超预期',
            point: 0
          },
          {
            label:'已达成',
            point: 0
          },
          {
            label:'已完成',
            point: 0
          },
          {
            label:'未完成扣B分',
            point: 0
          },
        ]
      },
      taskFormRules: taskFormRules,

      accessEnabled: {
        add: 0,
        delete: 0,
        excel_import: 0,
        edit: 0
      }
    }
  },
  methods: {
    set_point_config:function(){
      if(this.point_config_show == true) {
        this.point_config_show = false
      }else{
        this.point_config_show = true
      }
    },
    dialogTaskClose: function() {
      const form = this.$refs['newTaskForm']
      form.clearValidate()
      this.dialogTaskVisible = false
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val
    },
    selectable(row, index) {
      // if (row.mode_type > 0) {
      return true
      // } else {
      // return false;
      // }
    },

    onFilePreView(file) {
      // 点击时查看文件
      const $ext_list = ['doc', 'docx', 'pptx', 'xls', 'xlsx', 'ppt', 'txt']
      const $ext_name = file.name.split('.')[1]
      if ($ext_list.indexOf($ext_name) >= 0) {
        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) {
        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) {
              this.openPhotoSwipe(
                ii,
                document.querySelectorAll('img[preview="' + file.uid + '"]')
              )

              return
            }
            ii++
          }
        }
      }
    },

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

    handleFilesSuccess(response, file, fileList) {
      this.$set(this.taskForm, 'file_list', fileList)
    },
    beforeFilesUpload(file) {
      const $ext_list = ['zip', 'rar']
      const $ext_name = file.name.split('.')[1]
      if ($ext_list.indexOf($ext_name) != -1) {
        const isLt20M = file.size / 1024 / 1024 < 20
        if (!isLt20M) {
          this.$message.warning('您上传的压缩包文件大于20M')
          return false
        }
      }
    },

    dialogTaskOpen: function(title, id) {
      this.activeName = 'first'
      const self = this
      this.dialogTaskTitle = typeof id === 'undefined' ? '新增绩效工作' : '修改绩效工作'
      this.dialogTaskVisible = true
      if (typeof id !== 'undefined') {
        this.taskForm['id'] = id
        self.taskFormApi = '/integral.php/performance_work/common_task_update'
        this.loadTaskInfo(id)
      } else {
        this.taskForm = {
          set_point_config:0,
          cycle_type: 0,
            name: '',
            remark: '',
            task_time: '',
            category_id:[],
            distribution_date:1,
            distribution_time:8,
            point: 0,
            file_list: [],
            point_config: [
            {
              label:'超预期',
              point: 0
            },
            {
              label:'已达成',
              point: 0
            },
            {
              label:'已完成',
              point: 0
            },
            {
              label:'未完成扣B分',
              point: 0
            },
          ]
        },
        self.taskFormApi = '/integral.php/performance_work/common_task_add'
      }
      this.$nextTick(() => {
        const form = this.$refs['newTaskForm']
        this.$previewRefresh()
        if (typeof id === 'undefined') {
          form.resetFields()
          form.clearValidate()
        }
      })
    },

    loadTaskInfo: function(id) {
      const self = this

      this.$http('get','/integral.php/performance_work/get_task_info',{id: id})
        .then(function(response) {
          if (response.status == 200) {
            let jsonData = response.data
            self.taskForm = jsonData.data
            if(self.taskForm.set_point_config == 1){
              self.point_config_show = true
            }else{
              self.point_config_show = false
            }
          }
        })
    },

    dialogTaskSend: function() {
      const self = this
      if (self.isRequest) {
        return
      }
      const form = this.$refs['newTaskForm']
      form.validate((valid, invalidFields) => {
        let taskForm = JSON.parse(JSON.stringify(self.taskForm))
        if(self.point_config_show){
          taskForm.set_point_config = 1
        }else{
          taskForm.set_point_config = 0
        }
        if(taskForm.category_id){
          taskForm.category_id = taskForm.category_id[taskForm.category_id.length - 1]
        }else{
          taskForm.category_id = 0
        }
        if(!taskForm.category_id){
          taskForm.category_id = 0
        }
        if (valid) {
          this.sendloading = true
          this.$http('post',self.taskFormApi,qs.stringify({ row: taskForm }),
            // headers: {
            //   'Content-Type': 'application/x-www-form-urlencoded'
            // }
          )
            .then(function(response) {
              self.sendloading = 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 == 1000) {
                  self.expiretime = ''
                  self.expiredate = ''
                  self.$message({
                    message: message,
                    type: 'success'
                  })
                  self.dialogTaskClose()
                  self.loadRuleList()
                } else {
                  self.$message({
                    message: message,
                    type: 'error'
                  })
                }
              } else {
                message = '服务器太忙了'
              }
            })
        } else {
          for(let i in invalidFields){
            self.$message.error(invalidFields[i][0].message)
            self.activeName = 'first'
            return false
          }
          return false
        }
      })
    },



    confirmMultipleDelete() {
      if (this.multipleSelection.length < 1) {
        return false
      }
      this.$confirm('确定要删除选中的任务吗?', '批量删除任务库任务', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const targetArr = []
          for (const index in this.multipleSelection) {
            targetArr.push(this.multipleSelection[index].id)
          }
          const targetIds = targetArr.join(',')
          this.deleteRule(targetIds, true)
        })
    },
    handleCheck(target, param) {
      this.textTip = ''
      const textTip = []
      this.$refs.tree.getCheckedNodes().forEach(item => {
        textTip.push(item.label)
      })
      this.textTip = textTip.join('、')
      if (param.checkedKeys.length == 0) {
        this.textTip = '选择积分分类筛选'
      }
      this.filter.category_id = param.checkedKeys
      this.onFilterChanged()
      this.show3 = false
    },
    category_manage_open() {
      const self = this
      this.$nextTick(() => {
        self.$refs['rule_category_manage_com'].loadCategoryTree()
      })
    },

    filterHandler: function(value) {
      if (typeof value.category !== 'undefined' && value.category.length == 0) {
        this.filter.category_id = []
      }
      if (typeof value.category !== 'undefined' && value.category.length > 0) {
        this.filter.category_id = value.category
      }

      this.onFilterChanged()
    },

    handleSizeChange(val) {
      this.pageLimit = val
      this.onFilterChanged()
    },
    RuleFormSubmit() {
      this.$refs['RuleDetailView'].submitForm('detailForm')
    },
    formReset() {
      const _this = this

      _this.$refs['RuleDetailView'].formClear()
    },

    onFilterChanged: function() {
      this.currentPage = 1
      this.loadRuleList()
    },
    dateTimeFormatter: function(row, column, cellValue) {
      return cellValue
        ? this.$moment(cellValue * 1000).format('YYYY-MM-DD HH:mm')
        : ''
    },
    remarkFormatter(row, column, cellValue) {
      return cellValue == 'null' ? '' : cellValue
    },
    loadPointType: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_point_types')
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.pointTypes = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        })
    },
    // 获取规则列表
    loadRuleList: function() {
      var self = this
      self.loading = true
      var params = {
        site_id: this.profile.site_id,
        page: this.currentPage,
        interval: this.pageLimit
      }
      for (const item in this.filter) {
        const value = this.filter[item]
        if (item == 'category_id') {
          if (!value || value.length == 0) {
            continue
          }

          //params[item] = value
           params[item] = value[value.length - 1];
        } else {
          const valueStr = value.toString()
          if (valueStr && valueStr.length > 0) {
            params[item] = valueStr
          }
        }
      }
      this.$http('get','/integral.php/performance_work/get_task_list',params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false
            var jsonData = response.data
            try {
              self.totalCount = jsonData.data.total
              self.tableData = jsonData.data.data
            } catch (err) {
              console.log(err)
            }
          }
        })
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false
      }
      this.loadRuleList()
    },
    onDismissCreateCategoryDialog: function() {
      var form = this.$refs['newCategoryForm']
      form.clearValidate()
      this.newCategoryForm = {
        name: '',
        pid: []
      }
    },
    onDismissEditCategoryDialog: function() {
      var form = this.$refs['categoryForm']
      form.clearValidate()
      this.categoryForm = {
        id: '',
        name: '',
        pid: []
      }
    },
    // 获取当前选择的积分分类信息
    loadCurrentCategoryInfo() {
      const categoryPath = this.filter.category_id
      if (!categoryPath || !categoryPath.length) {
        return
      }
      const categoryId = categoryPath[categoryPath.length - 1]
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_category_info',{id: categoryId})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.parentCategoryTree = jsonData.tree
              self.categoryForm.id = jsonData.category_info.id
              self.categoryForm.name = jsonData.category_info.name
              if (jsonData.path) {
                const pathStrArray = jsonData.path.split(',')
                const pathArray = pathStrArray.map(data => {
                  return +data
                })
                self.categoryForm.pid = pathArray
              } else {
                self.categoryForm.pid = []
              }
              self.dialogEditCategoryVisible = true
            } catch (err) {
              console.log(err)
            }
          }
        })
    },
    loadCategoryTree: function() {
      var self = this
      this.$http('get','/integral.php/performance_work/task_category_tree',{site_id: this.profile.site_id})
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.categoryTree = jsonData.data
            } catch (err) {
              console.log(err)
            }
          }
        })
    },
    submitCreateCategoryForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendCreateCategoryRequest()
          }
        } else {
          return false
        }
      })
    },
    submitEditCategoryForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.submitEditCategoryForm(form)
          }
        } else {
          return false
        }
      })
    },
    sendCreateCategoryRequest: function() {
      const dataObj = this.newCategoryForm
      const formData = {}
      for (const item in dataObj) {
        if (item == 'pid') {
          const length = dataObj[item].length
          formData[item] = length == 0 ? 0 : dataObj[item][length - 1]
        } else {
          if (!dataObj[item]) {
            continue
          }
          formData[item] = dataObj[item]
        }
      }
      var self = this
      this.$http('post','/integral.php/performance_work/task_category_add',formData,'','',
        {transformRequest: [
          data => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(
                encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
              )
            }
            return paramArray.join('&')
          }
        ]},
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded'
        // }
      )
        .then(function(response) {
          let message = ''
          let status = 0

            const data = response.data


          self.$message({
            message: data.msg,
            type: data.code == 1000 ? 'success' : 'error'
          })
          if (data.code == 1000) {
            self.loadCategoryTree()
            self.dialogCreateCategoryVisible = false
          }
        })
    },
    submitEditCategoryForm: function() {
      const dataObj = this.categoryForm
      const formData = {}
      for (const item in dataObj) {
        if (item == 'pid') {
          const length = dataObj[item].length
          formData[item] = length == 0 ? 0 : dataObj[item][length - 1]
        } else {
          if (!dataObj[item]) {
            continue
          }
          formData[item] = dataObj[item]
        }
      }
      var self = this
      this.$http('post','/integral.php/ajax_request_common/update_integral_category',formData,'','',
        {transformRequest: [
          data => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(
                encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
              )
            }
            return paramArray.join('&')
          }
        ]},
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded'
        // }
      )
        .then(function(response) {
          let message = ''
          let status = 0
          if (response.status == 200) {
            const data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            switch (status) {
              case 1:
                message = '修改分类成功'
                break
              case -1:
                message = '表单参数错误'
                break
              case -2:
                message = '该分类名称已经存在，请改用其他名称'
                break
              case -3:
                message = '分类结构冲突，不能将子分类设置为从属分类'
                break
              default:
                message = '修改分类失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.loadRuleList()
            self.loadCategoryTree()
            self.dialogEditCategoryVisible = false
          }
        })
    },
    confirmDelete: function(ruleId) {
      this.$confirm(
        '确定要删除任务库任务吗？',
        '删除任务',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.deleteRule(ruleId)
        })
    },
    deleteRule: function(ruleId) {
      if (!ruleId) {
        return false
      }
      const params = {
        id: ruleId
      }
      var self = this
      this.$http('get','/integral.php/performance_work/common_task_multiple_del',params)
        .then(function(response) {
          var message = ''
          if (response.status == 200) {
            message = response.data.msg
            var data = response.data
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: data.code == 1000 ? 'success' : 'error'
          })
          if (data.code == 1000) {
            self.loadRuleList()
          }
        })
    },
    deleteCategory: function() {
      if (!this.categoryForm.id) {
        return false
      }
      const params = {
        id: this.categoryForm.id
      }
      var self = this
      this.$http('get','/integral.php/ajax_request_common/delete_integral_category',params)
        .then(function(response) {
          var message = ''
          var status = 0
          if (response.status == 200) {
            var data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            switch (status) {
              case 1:
                message = '删除积分分类成功'
                break
              case -1:
                message = '表单参数错误'
                break
              default:
                message = data.info ? data.info : '删除积分分类失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.loadCategoryTree()
            self.dialogEditCategoryVisible = false
          }
        })
    },
    toDetailPage: function(id, event) {
      const self = this
      this.RuleDetailDialogVisible = true
      this.$nextTick(() => {
        if (id > 0) {
          self.$refs['RuleDetailView'].editMode = true
          self.$refs['RuleDetailView'].loadRuleDetail(id)
        } else {
          self.$refs['RuleDetailView'].editMode = false
        }
      })
      return
    },
    saveStorage: function() {
      const storage = {
        filter: this.filter
      }
      this.$emit('set-storage', storage)
    },
    loadRuleDetail: function(ruleId) {
      const params = {
        id: ruleId
      }
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_rule_info',params)
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              // jsonData.remark == 'null'?'':jsonData.remark;
              self.ruleForm = jsonData
              self.dialogRuleVisible = true
            } catch (err) {
              console.log(err)
            }
          }
        })
    },
    generatePointIndication: function(item) {
      const propertyText = item.is_negative == 1 ? '扣除' : '奖励'
      const valueText =
        item.is_range == 1 ? item.value_1 + '～' + item.value_2 : item.value_1
      let typeText = ''
      for (let index = 0; index < this.pointTypes.length; index++) {
        const pointType = this.pointTypes[index]
        if (item.point_type == pointType.value) {
          typeText = pointType.label
          break
        }
      }
      return '标准： ' + propertyText + '  ' + valueText + '  ' + typeText
    },
    clearRuleForm: function() {
      this.ruleForm = {}
    },
    // 获取具体权限（对积分管理员/公司管理员生效）
    loadAccessItemFlag: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_access_flag',{id: this.profile.id,page_name: 'rule_master'})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.accessEnabled = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        })
    },
    // 上传文件
    uploadFile: function(params) {
      if (!params || !params.file) {
        return false
      }
      const formData = new FormData()
      formData.append('uploader_id', this.profile.id)
      formData.append('file', params.file)
      this.$http('post','/integral.php/excel_util/import_rule_sheet', formData,'','multipart/form-data',
          // headers: {
          //   'Content-Type': 'multipart/form-data'
          // },
          {transformRequest: [
            function(data) {
              return data
            }
          ]}
        )
        .then(response => {
          const responseData = response.data
          if (responseData.errors && responseData.errors.length > 0) {
            const messageHead = responseData.info
              ? responseData.info
              : '导入完成'
            const h = this.$createElement
            const errorGroup = [
              h('p', null, messageHead + '。但文件中存在如下问题数据：')
            ]

            errorGroup.push(
              h(
                'span',
                {
                  style: {
                    color: '#fff',
                    float: 'left',
                    width: '33%',
                    backgroundColor: 'rgb(126,148,245)',
                    padding: '5px 0 5px 10px'
                  }
                },
                '行数'
              )
            )
            errorGroup.push(
              h(
                'span',
                {
                  style: {
                    color: '#fff',
                    float: 'left',
                    width: '67%',
                    backgroundColor: 'rgb(126,148,245)',
                    padding: '5px 0'
                  }
                },
                '错误原因'
              )
            )
            // errorGroup.push(h('span',{style:{color:'#fff',float:'left',width:'33%',backgroundColor:'rgb(126,148,245)',padding:'5px 0'}},'内容错误'))
            for (let i = 0; i < responseData.errors.length; i++) {
              // errorGroup.push(h('div', {style:{width:'100%',padding:'8px 0 8px 10px',borderBottom:'1px solid #ccc',overflow:'hidden'}}, responseData.errors[i]));
              errorGroup.push(
                h(
                  'div',
                  {
                    style: {
                      float: 'left',
                      width: '33%',
                      padding: '8px 0 8px 10px',
                      borderBottom: '1px solid #ccc',
                      overflow: 'hidden'
                    }
                  },
                  '第' + responseData.errors_array[i].line + '行'
                )
              )
              errorGroup.push(
                h(
                  'div',
                  {
                    style: {
                      float: 'left',
                      width: '67%',
                      padding: '8px 0',
                      borderBottom: '1px solid #ccc',
                      overflow: 'hidden'
                    }
                  },
                  responseData.errors_array[i].msg
                )
              )
            }
            const message = h(
              'div',
              { style: { overflow: 'hidden' }},
              errorGroup
            )
            this.$alert(message, '导入结果', {
              confirmButtonText: '确定'
            })
          } else {
            this.$message({
              message: responseData.info ? responseData.info : '导入完成',
              type: responseData.status == 1 ? 'success' : 'error'
            })
          }
          if (responseData.status == 1) {
            this.loadRuleList()
          }
        })
        .catch(function(error) {
          return false
        })
    },
    // 下载文件
    downloadSheet: function() {
      const url =
        this.serverdomain +
        '/integral.php/excel_util/export_rule_sheet?site_id=' +
        this.profile.site_id
      window.open(url)
    },
    // 下载模板
    downloadTemplate: function() {
      const url =
        this.serverdomain +
        '/integral.php/excel_util/download_rule_template?site_id=' +
        this.profile.site_id
      window.location.href = url
    }
  },
  created() {
    if (this.profile.manager_type < 3) {
      this.loadPointType()
    }
    this.loadRuleList()
    this.loadCategoryTree()
    if (this.profile.manager_type == 4) {
      this.accessEnabled = {
        add: 1,
        delete: 1,
        excel_import: 1,
        edit: 1
      }
    } else if (this.profile.manager_type > 1) {
      this.loadAccessItemFlag()
    }

    this.$nextTick(() => {
      document.querySelector('#app').addEventListener('click', () => {
        if (this.show3) {
          this.show3 = false
        }
      })
    })
  }
}
</script>
<style>
.el-pagination {
  text-align: center;
  margin-top: 15px;
  background-color: #fff;
}
.ruleEditBox .el-dialog__header {
  display: none;
}

.arrRotation {
  transform: rotate(180deg);
}
.treeActice {
  color: #606266;
}
.el-tree-node__content {
  height: 34px;
}
</style>
