<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
        v-if="false"
        clearable
        :options="categoryTree"
        change-on-select
        v-model="filter.category_id"
        @change="onFilterChanged"
        placeholder="选择分类进行筛选或编辑"
        class="gap-right-8 first-element-btn"
      ></el-cascader>

      <div style="position:relative; display:inline-block;" @click.stop="show3 = !show3">
        <el-button style="color:rgb(192 196 204); padding-right:25px;">
          <span
            style="max-width: 150px; display: inline-block; overflow: hidden;"
            :class="{'treeActice':textTip != '选择积分分类筛选'}"
          >{{textTip}}</span>
          <span class="el-input__suffix">
            <span class="el-input__suffix-inner">
              <i :class="{'arrRotation': show3}" class="el-input__icon el-icon-arrow-down"></i>
            </span>
          </span>
        </el-button>
        <el-collapse-transition>
          <div
            v-show="show3"
            style="margin-top:10px;
            padding:6px 0;
             max-height:250px;
             min-width: 180px;
             overflow: auto;
             position:absolute;
             z-index:99;
             border: 1px solid #e4e7ed;
             border-radius: 2px;
             background:#fff;
             box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);"
          >
            <el-tree
              node-key="value"
              ref="tree"
              :data="categoryTree"
              :accordion="true"
              :highlight-current="true"
              :props="defaultProps"
              show-checkbox
              @check="handleCheck"
            ></el-tree>
          </div>
        </el-collapse-transition>
      </div>

      <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="toDetailPage(0, $event)"
        v-show="accessEnabled.add == 1"
        type="primary"
        plain
      >新增规则</el-button>

      <el-button
        @click="dialogExcelVisible = true"
        v-show="accessEnabled.excel_import == 1"
        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">
          <el-popover trigger="hover" placement="top">
            <p>{{ scope.row.items }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium" style="white-space: normal; overflow: hidden;">{{ scope.row.items }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        :formatter="remarkFormatter"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="创建时间" sortable>
        <template slot-scope="scope">
          <i v-if="scope.row.create_time" class="el-icon-time"></i>
          <span>{{dateTimeFormatter('','',scope.row.create_time)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间" sortable>
        <template slot-scope="scope">
          <i v-if="scope.row.modify_time" class="el-icon-time"></i>
          <span>{{dateTimeFormatter('','',scope.row.modify_time)}}</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="toDetailPage(scope.row.id, $event)"
              :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 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"
    >
      <rule-category-manage ref="rule_category_manage_com"></rule-category-manage>
    </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>
  </div>
</template>
<script>
  import RuleCategoryManage from '@/views/integral/RuleCategoryManage'
  import RuleDetail from '@/views/integral/RuleDetail'

  export default {
    components: {
      RuleCategoryManage,
      RuleDetail
    },

    data() {
      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 {
        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
        },

        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' }]
        },
        accessEnabled: {
          add: 0,
          delete: 0,
          excel_import: 0,
          edit: 0
        }
      }
    },
    methods: {
      handleSelectionChange: function(val) {
        this.multipleSelection = val
      },
      selectable(row, index) {
        // if (row.mode_type > 0) {
        return true
        // } else {
        // 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)
          })
          .catch(() => {
            // console.log('已取消删除');
          })
      },
      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)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      // 获取规则列表
      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/ajax_request_common/get_integral_rules',params)
          .then(function(response) {
            if (response.status == 200) {
              self.loading = false
              var jsonData = response.data
              try {
                self.status_list = jsonData.filter_list.category
                self.totalCount = jsonData.total_count
                self.tableData = jsonData.list_data
              } catch (err) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      changePage: function(current) {
        if (isNaN(current) || current < 1) {
          return false
        }
        this.loadRuleList()
      },
      onDismissCreateCategoryDialog: function() {
        console.log(242425472424)

        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)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      loadCategoryTree: function() {
        var self = this
        this.$http('get','/integral.php/ajax_request_common/get_integral_category_list_cascaded',{site_id: this.profile.site_id})
          .then(function(response) {
            if (response.status == 200) {
              const jsonData = response.data
              try {
                self.categoryTree = jsonData
              } catch (err) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      submitCreateCategoryForm: function(formName) {
        var form = this.$refs[formName]
        var self = this
        form.validate(valid => {
          if (valid) {
            if (form) {
              self.sendCreateCategoryRequest()
            }
          } else {
            // console.log('验证未通过');
            return false
          }
        })
      },
      submitEditCategoryForm: function(formName) {
        var form = this.$refs[formName]
        var self = this
        form.validate(valid => {
          if (valid) {
            if (form) {
              self.submitEditCategoryForm(form)
            }
          } else {
            // console.log('验证未通过');
            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]
          }
        }
        formData['site_id'] = this.profile.site_id
        var self = this
        this.$http('post','/integral.php/ajax_request_common/add_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
                default:
                  message = '新建分类失败'
              }
            } else {
              message = '服务器出现问题'
            }
            self.$message({
              message: message,
              type: status == 1 ? 'success' : 'error'
            })
            if (status == 1) {
              self.loadCategoryTree()
              self.dialogCreateCategoryVisible = false
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      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
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      confirmDelete: function(ruleId) {
        this.$confirm(
          '确定要删除此积分规则吗？附属的积分细则也会一并删除',
          '删除积分规则',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(() => {
            this.deleteRule(ruleId)
          })
          .catch(() => {
            // console.log('已取消删除');
          })
      },
      deleteRule: function(ruleId) {
        if (!ruleId) {
          return false
        }
        const params = {
          id: ruleId
        }
        var self = this
        this.$http('get','/integral.php/ajax_request_common/delete_integral_rule',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.loadRuleList()
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      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
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      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
                console.log(self.ruleForm)
                self.dialogRuleVisible = true
              } catch (err) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      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
                console.log('self.accessEnabled-------??')
                console.log(self.accessEnabled)
              } catch (err) {
                console.log(err)
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      },
      // 上传文件
      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) {
            console.log(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() {
      console.log(this.profile)
      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>
