<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入标签名称" />
      <el-select v-model="listQuery.labelType" clearable style="width: 200px" class="filter-item" placeholder="请选择标签类型">
        <el-option v-for="type in typeOptions" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>
      <el-button v-permission="['GET /admin/dmLabel/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/dmLabel/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="标签名称" prop="labelName" />

      <el-table-column align="center" label="类型" prop="type">
        <template slot-scope="scope">{{ scope.row.labelType | formatType }}</template>
      </el-table-column>

      <el-table-column align="center" label="对应数据表列-描述" prop="labelColumnName" />
      <el-table-column align="center" label="对应数据表列名" prop="labelColumn" />

      <el-table-column align="center" label="是否启用" prop="deleted">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deleted ? 'success' : 'error' ">{{ scope.row.deleted ? '不启用' : '启用' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="备注" prop="remark" />

      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/dmLabel/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/dmLabel/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="150px" style="width: 500px; margin-left:50px;">
        <el-form-item label="标签名称" prop="labelName">
          <el-input v-model="dataForm.labelName" />
        </el-form-item>
        <el-form-item label="标签类型" prop="labelType">
          <el-select v-model="dataForm.labelType" @change="handleTypeChange">
            <el-option v-for="type in typeOptions" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>

        <el-form-item v-show="dataForm.labelType === 9" label="自定义SQL" prop="labelSql">
          <el-input v-model="dataForm.labelSql" />
        </el-form-item>

        <el-form-item v-show="dataForm.labelType != 9" label="对应数据表列描述" prop="labelColumnName">
          <el-input v-model="dataForm.labelColumnName" />
        </el-form-item>

        <el-form-item v-show="dataForm.labelType != 9" label="对应数据表列" prop="labelColumn">
          <el-input v-model="dataForm.labelColumn" />
        </el-form-item>

        <el-form-item label="列属性">
          <el-radio-group v-model="dataForm.labelColumnProperty">
            <el-radio :label="0">字符串</el-radio>
            <el-radio :label="1">整型</el-radio>
            <el-radio :label="2">日期</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-show="dataForm.labelColumnProperty != 2" label="取值范围" prop="labelValueStart">
          <div style="display:flex">
            <el-input v-show="dataForm.labelColumnProperty != 2" v-model="dataForm.labelValueStart" />
            <el-input v-show="dataForm.labelColumnProperty == 1" v-model="dataForm.labelValueEnd" />
          </div>
        </el-form-item>

        <el-form-item v-show="dataForm.labelColumnProperty==2" label="日期范围" prop="dateArray">
          <el-date-picker
            v-model="dataForm.dateArray"
            type="daterange"
            class="filter-item"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">修改</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { listLabel, createLabel, updateLabel, deleteLabel } from '@/api/label'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const defaultTypeOptions = [
  {
    label: '客户',
    value: 0
  },
  {
    label: '电访结果',
    value: 1
  },
  {
    label: '线索',
    value: 2
  },
  {
    label: '订单',
    value: 3
  },
  {
    label: '自定义',
    value: 9
  }
]

const defaultStatusOptions = [
  {
    label: '正常',
    value: false
  },
  {
    label: '已下架',
    value: true
  }
]

export default {
  name: 'LabelSetting',
  components: { Pagination },
  filters: {
    formatType(type) {
      for (let i = 0; i < defaultTypeOptions.length; i++) {
        if (type === defaultTypeOptions[i].value) {
          return defaultTypeOptions[i].label
        }
      }
      return ''
    },
    formatType(type) {
      if (type === 0) {
        return '客户'
      } else if (type === 1) {
        return '电访结果'
      } else if (type === 2) {
        return '线索'
      } else {
        return '订单'
      }
    },
    formatStatus(status) {
      if (status === 0) {
        return '正常'
      } else if (status === 1) {
        return '已过期'
      } else {
        return '已下架'
      }
    }
  },
  data() {
    return {
      typeOptions: Object.assign({}, defaultTypeOptions),
      statusOptions: Object.assign({}, defaultStatusOptions),
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        labelType: undefined,
        deleted: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        id: undefined,
        labelValueStart: undefined,
        labelValueEnd: undefined,
        dateArray: [],
        deleted: false,
        labelName: undefined,
        labelType: 0,
        labelColumn: undefined,
        labelColumnProperty: 0,
        labelColumnName: undefined,
        labelSql: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        labelName: [{ required: true, message: '标签标题不能为空', trigger: 'blur' }],
        labelColumn: [{ required: true, message: '数据表列名不能为空', trigger: 'blur' }],
        labelColumnName: [{ required: true, message: '列名不能为空', trigger: 'blur' }],
        labelValueStart: [{ required: true, message: '取值范围不能为空', trigger: 'blur' }],
        labelValueEnd: [{ required: true, message: '取值范围不能为空', trigger: 'blur' }],
        dateArray: [{ required: true, message: '取值范围不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listLabel(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleTypeChange(value) {

    },
    validateDate(rule, value, callback) {
      if (value == '' || value == undefined || value == null) {
        if ((!reg.test(value)) && value != '') {
          callback(new Error('请输入日期取值范围'))
        }
      } else {
        callback()
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        labelName: undefined,
        labelValueStart: undefined,
        labelValueEnd: undefined,
        dateArray: [],
        labelType: 0,
        deleted: false,
        labelColumn: undefined,
        labelColumnProperty: 0,
        labelColumnName: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createLabel(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建标签成功，数据筛选大约在10分钟后完成'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if (this.dataForm.days === 0) {
          this.dataForm.daysType = 1
        } else {
          this.dataForm.daysType = 0
        }
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateLabel(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新优惠券成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      deleteCoupon(row)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '停用标签成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleDetail(row) {
      this.$router.push({ path: '/promotion/couponDetail', query: { id: row.id }})
    }
  }
}
</script>
