<template>
  <div class="app-container">
    <el-button
      type="primary"
      size="mini"
      style="margin-bottom:20px"
      @click="handleAdd()"
    >新增规则</el-button>
    <el-table :data="list" border style="width: 100%">

      <el-table-column label="规则名称" prop="name" />
      <el-table-column label="规则类型" prop="ruleType">
        <template slot-scope="scope">
          <span>{{
            scope.row.ruleType | optionsFilter(ruleTypeOptions)
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间">
        <template slot-scope="scope">
          <span>{{
            scope.row.createDate | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="最后更新时间">
        <template slot-scope="scope">
          <span>{{
            scope.row.lastUpdateDate | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" align="center" width="280px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            round
            style="font-size:14px;padding:10px 20px"
            @click="handleAdd(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            round
            style="font-size:14px;padding:10px 20px"
            @click="handleDel(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="listQuery.lastPageIndex"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog
      class="dialog"
      :title="diaTitle"
      append-to-body
      center
      width="604px"
      :visible.sync="diaVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :close="closeDia"
    >
      <div class="preview-container">
        <el-form
          ref="form"
          label-position="left"
          label-width="150px"
          :rules="rules"
          :model="form"
        >
          <el-form-item label="规则名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="规则类型" prop="ruleType">
            <el-select v-model="form.ruleType">
              <el-option v-for="item of ruleTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.ruleType === 'TEMPORARY'" label="生效时间" prop="dateRange">
            <el-date-picker
              v-model="form.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="行政区域" prop="regionIds">
            <el-cascader
              v-model="form.regionIds"
              class="filter-item"
              style="width:240px"
              :options="regions"
              :props="{ checkStrictly: true }"
              placeholder="行政区域"
              clearable
            />
          </el-form-item>
          <el-form-item label="是否适用于子级区域" prop="all">
            <el-radio v-model="form.all" :label="true">是</el-radio>
            <el-radio v-model="form.all" :label="false">否</el-radio>
          </el-form-item>

          <el-form-item v-if="form.ruleType === 'FINAL'" label="商户结算具体要求" prop="specialBusinessContent">
            <el-input
              v-model="form.specialBusinessContent"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item v-if="form.ruleType === 'FINAL'" label="商户结算积分最低限额" prop="specialBusinessMin">
            <el-input
              v-model="form.specialBusinessMin"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>

          <el-form-item label="申请办件积分" prop="apply">
            <el-input
              v-model="form.apply"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="处理办件积分" prop="handling">
            <el-input
              v-model="form.handling"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="差评扣分(负数)" prop="negativeComment">
            <el-input
              v-model="form.negativeComment"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="阅读" prop="read">
            <el-input
              v-model="form.read"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="实名认证积分" prop="realNameAuthentication">
            <el-input
              v-model="form.realNameAuthentication"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="发朋友圈" prop="sendACircleOfFriends">
            <el-input
              v-model="form.sendACircleOfFriends"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="特殊工单类型奖励积分(医保卫生)" prop="specialWorkType">
            <el-input
              v-model="form.specialWorkType"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="超期办件扣分(负数)" prop="timeOut">
            <el-input
              v-model="form.timeOut"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="非常满意得分" prop="verySatisfied">
            <el-input
              v-model="form.verySatisfied"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="default" @click="closeDia">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { list, add, del } from '@/api/fingertipIntegral'
import { getRegions } from '@/api/region'
export default {
  components: { Pagination },
  filters: {
    optionsFilter(value, options = []) {
      const findItem = options.find((option) => option.value === value)
      if (findItem) {
        return findItem.label
      }
      return ''
    }
  },
  data() {
    return {
      total: 0,
      listQuery: {
        lastPageIndex: 1,
        // params: {},
        size: 10
      },
      list: undefined,

      diaTitle: '',
      diaVisible: false,
      form: {
        name: undefined,
        ruleType: 'FINAL',
        regionIds: undefined,
        all: false,
        dateRange: undefined,

        apply: undefined,
        handling: undefined,
        negativeComment: undefined,
        read: undefined,
        realNameAuthentication: undefined,
        sendACircleOfFriends: undefined,
        specialWorkType: undefined,
        timeOut: undefined,
        verySatisfied: undefined,

        specialBusinessContent: undefined,
        specialBusinessMin: undefined
      },
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        ruleType: [{ required: true, message: '请选择', trigger: 'change' }],
        regionIds: [{ required: true, message: '请选择', trigger: 'change' }],
        all: [{ required: true, message: '请选择', trigger: 'change' }],
        dateRange: [{ required: true, message: '请选择', trigger: 'change' }],

        specialBusinessContent: [{ required: true, message: '请输入', trigger: 'change' }],
        specialBusinessMin: [{ required: true, message: '请输入', trigger: 'change' }]
      },

      ruleTypeOptions: [
        {
          label: '长期规则',
          value: 'FINAL'
        },
        {
          label: '临时规则',
          value: 'TEMPORARY'
        }
      ],
      regions: []
    }
  },
  watch: {
    'listQuery.lastPageIndex': {
      handler(val) {
        this.getList()
      },
      deep: true // true 深度监听
    }
  },
  created() {
    this.getRegions()
    this.getList()
  },
  methods: {
    getList() {
      list(this.listQuery).then(res => {
        // console.log(res);
        this.list = res.d
        this.total = res.d.total
        this.pageSize = res.d.pageSize
        // if (!res.d.lastPageIndex) {
        //   this.listQuery.lastPageIndex;
        // }
      })
    },
    getRegions() {
      getRegions().then(res => {
        const tempData = res.d
        const countyArr = [] // 县,1
        tempData.map(county => {
          const countyObj = {
            value: county.root.id,
            label: county.root.name,
            disabled: !county.root.check,
            children: []
          }
          countyArr.push(countyObj)
          county.node.map(town => {
            const townObj = {
              value: town.root.id,
              label: town.root.name,
              disabled: !town.root.check,
              children: []
            }
            countyObj.children.push(townObj)
            town.node.map(country => {
              townObj.children.push({
                value: country.root.id,
                label: country.root.name,
                disabled: !country.root.check
              })
            })
          })
        })
        this.regions = countyArr
      })
    },
    handleAdd(item) {
      if (item) {
        this.diaTitle = '编辑规则'
        const tmpItem = JSON.parse(JSON.stringify(item))
        const { regionIds, startDate, endDate } = tmpItem
        tmpItem.regionIds = regionIds.split(',')
        if (startDate || endDate) {
          tmpItem.dateRange = [new Date(startDate * 1000), new Date(endDate * 1000)]
        }
        this.form = tmpItem
      } else {
        this.diaTitle = '新增规则'
        this.form = {
          name: undefined,
          ruleType: 'FINAL',
          regionIds: undefined,
          all: false,
          dateRange: undefined,

          apply: undefined,
          handling: undefined,
          negativeComment: undefined,
          read: undefined,
          realNameAuthentication: undefined,
          sendACircleOfFriends: undefined,
          specialWorkType: undefined,
          timeOut: undefined,
          verySatisfied: undefined,

          specialBusinessContent: undefined,
          specialBusinessMin: undefined
        }
      }
      this.$nextTick(() => {
        const formEl = this.$refs['form']
        if (formEl) formEl.clearValidate()
        this.diaVisible = true
      })
    },
    submitForm() {
      // console.log(this.form)
      // return
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const { dateRange } = this.form
          const form = JSON.parse(JSON.stringify(this.form))
          const { regionIds = [] } = form
          form.regionIds = regionIds.join(',')
          if (dateRange) {
            form.startDate = dateRange[0].getTime() / 1000
            form.endDate = dateRange[1].getTime() / 1000
          }
          add(form).then(() => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.closeDia()
            this.getList()
          })
        }
      })
    },
    handleDel(item) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({ id: item.id }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      })
    },
    jumpStaff(item) {
      const { name, id } = item
      this.$router.push({
        path: '/dept/staff',
        query: {
          name,
          id
        }
      })
    },
    closeDia() {
      this.diaVisible = false
    }
  }
}
</script>

<style></style>
