<template>
  <div>
    <ai-list>
      <template #content>
        <div class="card_list">
          <div class="card" v-for="(item,index) in cardList" :key="index">
            <h2>{{ item.label }}</h2>
            <p class="color1">{{ item.value || 0 }}</p>
          </div>
        </div>
        <ai-title title="评分列表"></ai-title>
        <ai-search-bar>
          <template #left>
            <el-button type="primary" icon="iconfont iconAdd" @click="handleAdd">添加</el-button>
            <ai-select
                v-model="search.type"
                @change="onChange"
                placeholder="请选择事件类型"
                :selectList="$dict.getDict('shopScoreType')">
            </ai-select>
            <ai-select
                v-model="search.listType"
                @change="(search.current = 1), getList()"
                placeholder="请选择自定义事件"
                :selectList="dictList">
            </ai-select>
            <ai-select
                v-model="search.status"
                @change="(search.current = 1), getList()"
                placeholder="请选择状态"
                :selectList="$dict.getDict('shopScoreEvent')">
            </ai-select>
          </template>
        </ai-search-bar>
        <ai-table
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="total"
            style="margin-top: 6px;"
            :current.sync="search.current"
            :size.sync="search.size"
            @getList="getList">

          <el-table-column
              label="分值"
              slot="score">
            <template v-slot="{ row }">
              <span>{{row.score === 0 ? 0 : row.score > 0 ? `+${row.score}` : row.score}}</span>
            </template>
          </el-table-column>
          <el-table-column
              label="状态"
              slot="status">
            <template v-slot="{ row }">
              <span class="start" v-if="row.status==='1'">启用</span>
              <span class="stop" v-else>停用</span>
            </template>
          </el-table-column>

          <el-table-column slot="options" width="180px" fixed="right" label="操作" align="center">
            <template slot-scope="{ row }">
              <div class="table-options">
                <el-button type="text" @click="changeState(row)">{{row.status === '1' ? '停用' : '启用'}}</el-button>
                <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                <el-button type="text" @click="handleDelete(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog title="评分规则" :visible.sync="dialog" width="800px" @closed="onClosed" @onConfirm="onConfirm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="事件类型：" prop="type">
          <ai-select
              v-model="form.type"
              placeholder="请选择事件类型"
              :selectList="$dict.getDict('shopScoreType')">
          </ai-select>
        </el-form-item>
        <el-form-item label="自定义事件：" prop="listType">
          <el-input v-model="form.listType" :disabled="form.type === '' || form.type === null || form.type === undefined" placeholder="请输入自定义事件" size="small"></el-input>
        </el-form-item>
        <el-form-item label="规则：">常规</el-form-item>
        <el-form-item label="分值：" prop="score">
          <el-input-number v-model="form.score" :precision="2" size="small" placeholder="请输入分值"></el-input-number>
        </el-form-item>
      </el-form>
    </ai-dialog>
  </div>

</template>

<script>
export default {
  name: "RuleManage",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  data() {
    return {
      search:{
        genre:'',
        type:'',
        status:'',
        current: 1,
        size: 10,
      },
      dictList:[],
      cardList: [
        {
          label: '规则总数量',
          value: 0
        },
        {
          label: '正向事件规则项',
          value: 0
        },
        {
          label: '正向事件总分数',
          value: 0
        },
        {
          label: '负向事件规则项',
          value: 0
        },
        {
          label: '负向事件总分数',
          value: 0
        },
      ],
      total: 10,
      colConfigs: [
        {type: "selection"},
        { prop: 'type',  label: '类型', align: 'center' ,render:(h,{row})=>{
          return h('span',null,this.dict.getLabel('shopScoreType',row.type))
          }},
        { prop: 'listType',  label: '事件', align: 'center' },
        { prop: 'rule',  label: '规则', align: 'center' },
        { slot: 'score' },
        { slot: 'status'},
      ],
      tableData: [],
      dialog:false,
      form:{
        id:null,
        listType:'',
        type:'',
        score:'',
        rule:'常规'
      },
      rules:{
        type:[{ required: true, message: '请选择事件类型', trigger: 'change' },],
        listType:[{ required: true, message: '请输入自定义事件', trigger: 'blur' },],
        score:[{ required: true, message: '请输入分值', trigger: 'change' },],
      }
    }
  },

  created(){
    this.$dict.load('shopScoreType','shopScoreEvent').then(()=>{
      this.getStatic()
      this.getList()
    })
  },

  methods: {
    onChange(e){
      if(e){
        this.queryListTypeByType(e)
      }else {
        this.search.listType = ''
       this.dictList = []
       this.search.current = 1
       this.getList()
      }
    },

    async queryListTypeByType(type){
      try {
        const {code,data} = await this.instance.post('/app/appscorerules/queryListTypeByType',null,{
         params:{
            type
          }
        })
        if(code===0){
          this.dictList = data?.map(item=>{
            return {
              dictName:item.listType,
              dictValue:item.listType
            }
          })
        }
      }catch (e) {
        console.log(e)
      }
    },

    onConfirm(){
      this.$refs['formRef'].validate(async valid=>{
        if(valid){
          try {
            const {code} = await this.instance.post('/app/appscorerules/addOrUpdate',{...this.form})
            if(code===0){
              this.$message.success('保存成功')
              this.dialog = false
              this.getList()
              this.getStatic()
            }
          }catch (e) {
            console.error(e)
          }
        }
      })
    },
    onClosed(){
      this.form = {
        type:'',
        score:''
      }
      this.$refs['formRef'].resetFields()
    },
    async changeState({id,status}){
      try {
        const {code} = await this.instance.post('/app/appscorerules/isOrNotEnableById',null,{
          params:{id}
        })
        if(code===0){
          this.$message.success(status === '1' ? '停用成功' :'启用成功')
          this.getStatic()
          this.getList()
        }
      }catch (e) {
        console.error(e)
      }
    },

    handleEdit(row){
      this.form = {...row}
      this.dialog = true
    },

    handleDelete({id}){
      this.$confirm("是否要删除此数据？").then(
        async ()=>{
          try {
            const {code} = await this.instance.post('/app/appscorerules/delete',null,{
              params:{ids:id}
            })
            if(code===0){
              this.$message.success('删除成功')
              this.getStatic()
              this.getList()
            }
          }catch (e) {
            console.error(e)
          }
        }
      )
    },

    handleAdd(){
      this.dialog = true
    },

    async getStatic() {
      try {
        const {code,data} = await this.instance.post('/app/appscorerules/queryAppScoreRulesCount')
        if(code===0){
          const array = ['rulesCount','positiveCount','positiveScore','negativeCount','negativeScore']
          array.forEach((item,index)=>{
            this.cardList[index].value = data[item]
          })
        }
      }catch (e) {
        console.error(e)
      }
    },

    async getList(){
      try {
        const {code,data} = await this.instance.post('/app/appscorerules/list',null,{
          params:{
            ...this.search
          }
        })
        if(code===0){
          this.tableData = data.records
          this.total = data.total
        }
      }catch (e) {
        console.error(e)
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.card_list {
  display: flex;

  .card {
    flex: 1;
    height: 96px;
    background: #F9F9F9;
    border-radius: 2px;
    margin-right: 20px;
    padding: 16px 24px;
    box-sizing: border-box;

    h2 {
      color: #888888;
      font-weight: 600;
      font-size: 16px;
    }

    p {
      margin-top: 8px;
      font-size: 24px;
      font-weight: 600;
    }

    .color1 {
      color: #2891FF;
    }

    .color2 {
      color: #22AA99;
    }

    .color3 {
      color: #F8B425;
    }
  }

  .card:last-child {
    margin-right: 0;
  }
}

:deep(.start){
  font-size: 14px;
  color: #2EA222;
}

:deep(.stop){
  font-size: 14px;
  color: #FF4466;
}
</style>
