<template>
  <a @click="loadWidgetData(showCreateDialog)" :class="{'integral-create-application-btn':true}">
    <el-button type="primary" plain v-if="btn_type == 1">积分申请</el-button>
    <el-dialog
      append-to-body
      title="积分申请"
      :visible.sync="dialogCreateVisible"
      :close-on-click-modal="false"
      @open="initialCreateDialog"
      width="650px"
    >
      <el-scrollbar
        wrap-class="column-wrapper scrollable-items-container"
        :native="false"
        style="height: 300px;"
      >
        <el-form
          ref="newApplicationForm"
          :model="newApplicationForm"
          :rules="rules"
          @submit.native.prevent
          style="padding-right:15px;"
        >
          <el-form-item label="事件日期" prop="event_time" :label-width="formLabelWidth">
            <el-date-picker
              v-model="newApplicationForm.event_time"
              type="date"
              value-format="timestamp"
              placeholder="选择日期"
              :picker-options="assistantOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="事件内容" prop="remark" :label-width="formLabelWidth">
            <el-input
              v-model="newApplicationForm.remark"
              auto-complete="off"
              placeholder="输入事件内容（最多100字）"
              type="textarea"
              :rows="3"
              resize="none"
              style="margin-top:5px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="审核人" prop="reviewer_id" :label-width="formLabelWidth">
            <template>
              <el-select
                :disabled="settings.review_set.indexOf('can_set_review') < 0"
                v-model="newApplicationForm.reviewer_id"
                placeholder="选择审核人"
              >
                <el-option
                  v-for="item in reviewerOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span>{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dept_name }}</span>
                </el-option>
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="附件上传" :label-width="formLabelWidth">
            <upload_oss
              :headers="Xtoken"
              class="avatar-uploader"
              :action="'https://'+'integralsys.oss-cn-shenzhen.aliyuncs.com'"
              :show-file-list="true"
              :file-list="newApplicationForm.file_list"
              :on-success="handleFilesSuccess"
              :on-preview="onFilePreView"
              :before-upload="beforeFilesUpload"
              :on-remove="onFileRemove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </upload_oss>
            <div style="display:none;">
              <img
                v-for="(item,index) in newApplicationForm.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
            v-if="settings.review_set.indexOf('can_set_category') >= 0"
            label="自主指定积分规则"
            prop="determine_rule"
            :label-width="formLabelWidth"
          >
            <el-switch class="gap-right-15" v-model="newApplicationForm.determine_rule"></el-switch>
          </el-form-item>
          <el-form-item
            label="积分分类"
            prop="category_id"
            :label-width="formLabelWidth"
            v-show="newApplicationForm.determine_rule"
          >
            <el-cascader
              clearable
              :options="categoryTree"
              change-on-select
              v-model="newApplicationForm.category_id"
              @change="loadAvailableRuleItems(newApplicationForm)"
              placeholder="选择积分分类"
            ></el-cascader>
          </el-form-item>
          <el-form-item
            label="积分规则"
            prop="rule_item_id"
            :label-width="formLabelWidth"
            v-show="newApplicationForm.determine_rule"
          >
            <el-select
              v-model="newApplicationForm.rule_item_id"
              @change="updatePointIndicatorInCreateDialog"
              :disabled="!newApplicationForm.category_id || newApplicationForm.category_id.length == 0"
            >
              <el-option-group
                v-for="group in availableRuleItems"
                :key="group.id"
                :label="group.name"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.id"
                  :label="item.content"
                  :value="item.id"
                ></el-option>
              </el-option-group>
            </el-select>
            <br>
            <span
              v-show="newApplicationForm.rule_item_id"
            >标准： {{ newApplicationForm.pointIndicatorText }}</span>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submitCreateForm('newApplicationForm')">确 定</el-button>
      </div>
    </el-dialog>
    <div class="card-panel" v-if="btn_type==0">
      <div class="tpzs2"></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 { getToken } from '@/utils/auth'
import qs from 'qs'
import preview from '@/views/dashboard/components/preview/lib/index'
import 'vue-photo-preview/dist/skin.css'
import data from "../../svg-icons/generateIconsView";
import upload_oss from '@/views/upload_oss/upload'

Vue.use(preview, {
  tapToClose: false
})
export default {
  components: { upload_oss },
  props: {
    btn_type: {
      type: Number,
      default: 0
    }
  },
  name: 'IntegralCreateApplicationBtn',
  data() {
    const validateRemark = (rule, value, callback) => {
      const validValue = value
        ? value.replace(/\s/g, '').replace(/&nbsp;/gi, '')
        : value
      if (!validValue) {
        return callback(new Error('请填写事件内容'))
      } else if (validValue.length < 2) {
        return callback(new Error('事件内容需要2个字以上'))
      } else {
        callback()
      }
    }
    const validateReviewer = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择审核人'))
      } else {
        callback()
      }
    }
    const validateCategory = (rule, value, callback) => {
      if (
        this.newApplicationForm.determine_rule &&
        (!value || value.length == 0)
      ) {
        return callback(
          new Error('您已勾选自主指定积分规则，请选择积分分类后再提交')
        )
      } else {
        callback()
      }
    }
    const validateRuleItem = (rule, value, callback) => {
      if (this.newApplicationForm.determine_rule && !value) {
        return callback(
          new Error('您已勾选自主指定积分规则，请选择积分规则后再提交')
        )
      } else {
        callback()
      }
    }
    return {
      loading: false,
      Xtoken: { 'X-Token': getToken() },
      settings: this.$store.getters.system_setting,
      profile: this.$store.getters.user_info,
      totalCount: 0,
      tableData: null,
      currentPage: 1,
      dialogCreateVisible: false,
      dialogEditVisible: false,
      pointTypes: [],
      filter: {
        keywords: '',
        point_type: 0,
        time_range: ''
      },
      newApplicationForm: {
        event_time: '',
        remark: '',
        determine_rule: false,
        category_id: [],
        rule_item_id: '',
        reviewer_id: '',
        pointIndicatorText: '',
        file_list: []
      },
      applicationForm: {
        id: '',
        event_time: '',
        remark: '',
        determine_rule: false,
        category_id: [],
        rule_item_id: '',
        reviewer_id: '',
        pointIndicatorText: ''
      },
      categoryTree: [],
      rules: {
        remark: [{ validator: validateRemark, trigger: 'change' }],
        reviewer_id: [{ validator: validateReviewer, trigger: 'change' }],
        category_id: [{ validator: validateCategory, trigger: 'change' }],
        rule_item_id: [{ validator: validateRuleItem, trigger: 'change' }]
      },
      rulesEdit: {
        remark: [{ validator: validateRemark, trigger: 'change' }]
      },
      formLabelWidth: '140px',
      assistantOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      instantPickerOptions: {
        shortcuts: [
          {
            text: '本周',
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString())
              const start =
                now.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000
              const end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '上周',
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString())
              const start =
                now.getTime() - (now.getDay() + 6) * 24 * 60 * 60 * 1000
              const end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '本月',
            onClick(picker) {
              const now = new Date()
              const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
              const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          },
          {
            text: '上月',
            onClick(picker) {
              const now = new Date()
              const startDate = new Date(
                now.getFullYear() - (now.getMonth() > 0 ? 0 : 1),
                (now.getMonth() + 11) % 12,
                1
              )
              const endDate = new Date(now.getFullYear(), now.getMonth(), 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          }
        ]
      },
      reviewerOptions: [],
      availableRuleItems: []
    }
  },
  methods: {
    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(
            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.newApplicationForm.file_list) {
          if (
            ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG'].indexOf(
              this.newApplicationForm.file_list[i].name.split('.')[1]
            ) >= 0
          ) {
            if (this.newApplicationForm.file_list[i].name == file.name) {
              this.openPhotoSwipe(
                ii,
                document.querySelectorAll('img[preview]')
              )
              return
            }
            ii++
          }
        }
      }
    },

    onFileRemove(file, fileList) {
      this.newApplicationForm.file_list = fileList
    },
    handleFilesSuccess(response, file, fileList) {
      this.newApplicationForm.file_list = fileList
      this.$set(this.newApplicationForm, 'file_list', fileList)
    },
    beforeFilesUpload() {},
    onFilterChanged: function() {
      this.currentPage = 1
      this.loadApplicationList()
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false
      }
      this.loadApplicationList()
    },
    dateFormatter: function(row, column, cellValue) {
      return this.$moment(cellValue * 1000).format('YYYY年MM月DD日')
    },
    dateTimeFormatter: function(row, column, cellValue) {
      return cellValue
        ? this.$moment(cellValue * 1000).format('YYYY-MM-DD HH:mm')
        : ''
    },
    reviewStatusFormatter: function(row, column, cellValue) {
      return cellValue == 1 ? '待审核' : '已生效'
    },
    initialCreateDialog: function() {
      if (!this.newApplicationForm.event_time) {
        this.newApplicationForm.event_time = new Date().getTime()
      }
      if (this.reviewerOptions.length > 0) {
        this.newApplicationForm.reviewer_id = this.reviewerOptions[0].id
      }
    },
    showCreateDialog: function() {
      this.dialogCreateVisible = true
    },
    updatePointIndicatorInCreateDialog: function(currentVal) {
      this.newApplicationForm.remark = this.generatePointIndicatorText(currentVal)

      this.newApplicationForm.pointIndicatorText = this.generatePointIndicator(
        currentVal
      )
    },
    updatePointIndicatorInEditDialog: function(currentVal) {
      this.applicationForm.pointIndicatorText = this.generatePointIndicator(
        currentVal
      )
    },
    generatePointIndicator: function(val) {
      for (let i = 0; i < this.availableRuleItems.length; i++) {
        for (let j = 0; j < this.availableRuleItems[i].options.length; j++) {
          const item = this.availableRuleItems[i].options[j]
          if (val == item.id) {
            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
              }
            }
            const indicatorText =
              propertyText + '  ' + valueText + '  ' + typeText
            return indicatorText
          }
        }
      }
    },

    generatePointIndicatorText: function(val) {
      for (let i = 0; i < this.availableRuleItems.length; i++) {
        for (let j = 0; j < this.availableRuleItems[i].options.length; j++) {
          const item = this.availableRuleItems[i].options[j]
          if (val == item.id) {
            return item.content
          }
        }
      }
    },

    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)
        })
    },
    // 获取控件所需数据
    loadWidgetData: function(callback) {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/prepare_integral_options',{
            id: this.profile.id,
            category_tree: 1,
            superior_list: 1}
          )
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.categoryTree = jsonData.category_tree
              self.reviewerOptions = jsonData.reviewer_list
              if (callback) {
                callback.call()
              }
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 选择积分分类时更新积分规则
    loadAvailableRuleItems: function(form) {
      const categoryPath = form.category_id
      if (!categoryPath || categoryPath.length == 0) {
        return
      }
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_grouped_rule_items',{
            category_id: categoryPath[categoryPath.length - 1]
          })
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.availableRuleItems = jsonData
              form.rule_item_id = ''
              form.pointIndicatorText = ''
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    processDetailData: function(object) {
      // 时间戳转换
      object.event_time *= 1000
      object.reviewer_id =
        !isNaN(object.reviewer_id) && object.reviewer_id > 0
          ? parseInt(object.reviewer_id)
          : ''
      if (
        !isNaN(object.rule_item_id) &&
        object.rule_item_id > 0 &&
        object.category_id
      ) {
        object.determine_rule = true
        object.category_id = object.category_id
          .toString()
          .split(',')
          .map(Number)
        object.rule_item_id = object.rule_item_id
        this.updatePointIndicatorInEditDialog(object.rule_item_id)
      } else {
        object.determine_rule = false
        object.category_id = []
        object.rule_item_id = ''
      }
      return object
    },
    submitCreateForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendCreateRequest()
          }
        } else {
          // console.log('验证未通过');
          return false
        }
      })
    },
    submitEditForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendEditRequest()
          }
        } else {
          // console.log('验证未通过');
          return false
        }
      })
    },
    sendCreateRequest: function() {
      this.loading = true
      const dataObj = JSON.parse(JSON.stringify(this.newApplicationForm))
      console.log(dataObj)
      // dataObj.file_list = qs.stringify(dataObj.file_list)
      const formData = {}
      for (const item in dataObj) {
        if (item == 'category_id' && dataObj.category_id.length > 0) {
          console.log('7666666')
          formData[item] = dataObj.category_id[dataObj.category_id.length - 1]
          continue
        }
        if (item == 'event_time') {
          formData[item] = parseInt(dataObj[item] / 1000)
        } else if (item == 'determine_rule') {
          formData[item] = dataObj[item] ? 1 : 0
        } else {
          formData[item] = dataObj[item]
        }
      }
      formData['applicant_id'] = this.profile.id
      var self = this
      this.$http('post','/integral.php/ajax_request_common/add_integral_application',qs.stringify(formData),
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded'
        // }
      )
        .then(function(response) {
          self.loading = false
          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 = '积分申请提交成功'
                self.$emit('sendsuccess')
                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.currentPage = 1
            self.dialogCreateVisible = false

            self.resetCreateDialog()
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    sendEditRequest: function() {
      const dataObj = this.applicationForm
      const formData = {
        id: dataObj.id,
        event_time: parseInt(dataObj.event_time / 1000),
        remark: dataObj.remark,
        determine_rule: dataObj.determine_rule ? 1 : 0,
        rule_item_id: dataObj.rule_item_id
      }
      var self = this
      this.$http('post','/integral.php/ajax_request_common/update_integral_application',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
              default:
                message = data.info ? data.info : '积分申请修改失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.loadApplicationList()
            self.dialogEditVisible = false
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    resetCreateDialog: function() {
      const form = this.$refs['newApplicationForm']

      this.newApplicationForm = {
        event_time: '',
        remark: '',
        determine_rule: false,
        category_id: [],
        rule_item_id: '',
        reviewer_id: '',
        pointIndicatorText: '',
        file_list: []
      }

      form.clearValidate()
      form.resetFields()
    },
    confirmDelete(eventId) {
      this.$confirm('确定要撤消此积分申请吗?', '撤消积分申请', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteItem(eventId)
        })
        .catch(() => {
          // console.log('已取消删除');
        })
    },
    deleteItem(eventId) {
      if (!eventId) {
        return false
      }
      var self = this
      this.$http('get','/integral.php/ajax_request_common/delete_integral_application',{id: eventId})
        .then(function(response) {
          let message = ''
          let 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.loadApplicationList()
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    }
  },
  created() {
    this.loadPointType()
  }
}
</script>

<style>
.integral-create-application-btn .tpzs2 {
  margin: 0 auto;
  width: 40px;
  height: 40px;
  background-image: url(/images/jfsq.png);
  background-size: 100%;
}
.integral-create-application-btn .card-panel-description {
  width: 100%;
  text-align: center;
  color: #666;
}
.integral-create-application-btn .card-panel-text {
  line-height: 40px;
  font-size: 20px;
  font-weight: bold;
}

.integral-create-application-btn .card-panel-text2 {
  font-size: 14px;
  line-height: 20px;
  color: rgba(102, 102, 102, 1);
}
</style>
