<template>
  <section class="list">
    <ai-list>
      <template #content>
        <ai-search-bar>
          <template #left>
            <el-button type="primary" size="small" icon="iconfont iconAdd" @click="changeIntegral('',0)">&nbsp;批量调整积分</el-button>
            <el-cascader ref="cascader1" clearable v-model="departIdList" :options="girdOptions" placeholder="所属部门" size="small"
              :props="defaultProps" :show-all-levels="false" @change="gridChange"></el-cascader>
          </template>
          <template #right>
            <!-- <ai-import :instance="instance" :dict="dict" type="appintegraluser" name="积分管理"
                      @success="getTableData()">
              <el-button icon="iconfont iconImport">导入</el-button>
            </ai-import> -->
            <ai-download :instance="instance" url="/app/appintegraluser/girdIntegralExport" :params="search" :fileName="menuName"
                         :disabled="tableData.length == 0">
            </ai-download>
            <el-input size="small" placeholder="姓名" v-model="search.name" clearable
              @clear="current = 1, search.name = '', getTableData()" suffix-icon="iconfont iconSearch"
              v-throttle="() => {(current = 1), getTableData();}"/>
          </template>
        </ai-search-bar>
        <ai-table :tableData="tableData" :total="total" :current.sync="current" :size.sync="size"
                  @getList="getTableData()" :col-configs="colConfigs" :dict="dict" @sort-change="changeTableSort">
          <el-table-column slot="options" label="操作"  align="center">
            <template slot-scope="{ row }">
              <el-button type="text" @click="changeIntegral(row,1)">调整积分</el-button>
              <el-button type="text" @click="toDetail(row.id)">详情</el-button>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog
        title="调整积分"
        :visible.sync="dialog"
        :destroyOnClose="true"
        width="720px"
        @onConfirm="onConfirm"
        @closed="form={},chooseUserList=[]">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择人员" prop="ids">
          <ai-person-select :instance="instance" :customClicker="true" :chooseUserList="chooseUserList"
              url="/app/wxcp/wxuser/list" headerTitle="人员列表"
              :isMultiple="true" dialogTitle="选择" @selectPerson="selectPerson" class="aipersonselect">
            <template name="option" v-slot:option="{ item }">
              <span class="iconfont iconProlife">{{ item.name }}</span>
              <ai-id mode="show" :show-eyes="false" :value="item.idNumber"/>
            </template>
          </ai-person-select>
        </el-form-item>
        <el-form-item label="调整说明" prop="eventDesc">
          <el-input v-model.trim="form.eventDesc" placeholder="请输入..." type="textarea" :rows="4" show-word-limit
                    maxlength="100"></el-input>
        </el-form-item>
        <el-form-item label="上传凭证">
          <ai-uploader :instance="instance" fileType="file" v-model="form.enclosure" :limit="1"></ai-uploader>
        </el-form-item>
        <el-form-item label="类型" prop="scoreCalcType">
          <ai-select v-model="form.scoreCalcType" :selectList="dict.getDict('integralCalcType')"/>
        </el-form-item>
        <el-form-item label="积分" prop="score">
          <el-input v-model.trim="form.score" placeholder="请输入正数" size="small"></el-input>
        </el-form-item>
      </el-form>
    </ai-dialog>
  </section>

</template>

<script>
import { mapState } from "vuex";
export default {
  name: "list",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    menuName:String
  },
  data() {
    return {
      search: {
        name: '',
        departId: '',
        current: 1,
        size: 10,
        // sortFiled: '',
        // sortRule: '',
      },
      departIdList: [],
      tableData: [],
      size: 10,
      total: 0,
      current: 1,
      girdList: [],
      form: {
        ids: [],
        eventDesc: "",
        enclosure: "",   // 附件
        scoreCalcType: "",
        score: '',
      },
      personList: [],
      dialog: false,
      girdOptions: [],
      defaultProps: {
        label: 'name',
        value: 'id',
        checkStrictly: true,
      },
      chooseUserList: [],
      flag: false,
    }
  },
  created() {
    this.$dict.load('integralCalcType')
    this.getTableData()
    this.getGridList()
  },
  computed: {
    ...mapState(['user']),
    colConfigs() {
      return [
        { prop: "name", label: '姓名', align: "left"},
        { prop: "departName", label: '所属部门' },
        { prop: "nowScore", label: '积分余额', align: "center" },
        // { prop: "totalIntegral", label: '累计积分', align: "center", sortable: "custom" },
        { prop: "usedIntegral", label: '已用积分', align: "center"  },
        { slot: "options" },
      ]
    },
    rules() {
      return {
        ids: [{required: true, message: '请选择人员', trigger: 'blur'}],
        eventDesc: [{required: true, message: '请输入调整说明', trigger: 'blur'}],
        scoreCalcType: [{required: true, message: '请选择类型', trigger: 'change'}],
        score: [{required: true, message: '请输入积分', trigger: 'blur' },
        {pattern: /^([1-9]\d*|0)(\.\d{1,2})?$/, message: '请输入正数且最多只能保留两位小数'}],
      }
    },
  },
  methods: {
    getTableData() {
      this.instance.post(`/app/appscoredetail/list`,null,{
        params: {
          ...this.search,
          current: this.current,
          size: this.size,
          total: this.total
        }
      }).then(res => {
        if(res?.data) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },

    selectPerson(val) {
      console.log(val)
      if (val) {
        this.personList = val
        this.form.ids = [...this.personList.map(e => e.sysUserId)]
      } else {
        this.form.ids = this.chooseUserList.map(e => e.sysUserId)
      }
    },
    changeIntegral(row,type) {
      if(type==0) {
        this.dialog = true
      } else if(type ==1) {
        this.chooseUserList = [{
          sysUserId: row.sysUserId,
          name: row.name
        }]
        this.form.ids = this.chooseUserList.map(e => e.sysUserId)
        this.dialog = true
      }
    },
    getGridList() {
      this.instance.post(`/app/wxcp/wxdepartment/listAll`).then((res) => {
        if (res.code == 0) {
          this.girdOptions = this.toTree(res.data)
        }
      })
    },

    // 转树形结构
    toTree(data) {
      let result = [];
      if (!Array.isArray(data)) {
        return result
      }
      let map = {};
      data.forEach(item => {
        map[item.id] = item;
      });
      data.forEach(item => {
        let parent = map[item.parentid];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },

    gridChange(val) {
      this.departIdList = val
      this.search.departId = val?.[val.length - 1]
      this.$refs.cascader1.dropDownVisible = false;
      this.getTableData()
    },

    changeTableSort(col) {
      if(col.prop === 'integral') { // 剩余积分
        this.search.sortFiled = 0
        if(col.order === 'ascending') {
          this.search.sortRule = true
        } else if(col.order === 'descending') {
          this.search.sortRule = false
        } else if(col.order === null) {
          this.search.sortRule = ''
        }
      } else if(col.prop === 'totalIntegral') {  // 累计积分
        this.search.sortFiled = 1
        if(col.order === 'ascending') {
          this.search.sortRule = true
        } else if(col.order === 'descending') {
          this.search.sortRule = false
        } else if(col.order === null) {
          this.search.sortRule = ''
        }
      } else if(col.prop === 'usedIntegral') {  // 已用积分
        this.search.sortFiled = 2
        if(col.order === 'ascending') {
          this.search.sortRule = true
        } else if(col.order === 'descending') {
          this.search.sortRule = false
        } else if(col.order === null) {
          this.search.sortRule = ''
        }
      }
      this.getTableData()
    },

    onConfirm() {
      if(this.flag) return

      if(this.form.file?.length) {
        this.form.enclosure = this.form.file[0].url
      }
      this.$refs.form.validate((valid)=> {
        if(valid) {
          this.flag = true
          this.instance.post(`/app/appscoredetail/changeScore`,{...this.form}).then(res => {
            if(res?.code == 0) {
              this.$message.success('调整积分成功')
              setTimeout(() =>{
                this.dialog = false
                this.getTableData()
                this.flag = false
              }, 600)
            } else {
              this.flag = false
            }
          })
        }
      })

    },

    toDetail(id) {
      this.$emit('change', {
        type: 'Detail',
        params: {
          id: id
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.list {
  height: 100%;

  :deep( .ai-dialog .ai-dialog__content ){
    max-height: 600px!important;
  }



  .userlist {
    display: inline-block;
  }

  .userlist, .user {
    display: inline-block;
  }

  .user {
    position: relative;
    width: 70px;
    text-align: center;

    .remove-icon {
      position: absolute;
      right: 7px;
      top: -4px;
      line-height: 1;
      padding: 6px 0;
      font-size: 16px;
      cursor: pointer;

      &:hover {
        color: crimson;
      }
    }

    img, h2 {
      display: block;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      margin: 0 auto 4px;
      font-size: 14px;
      color: #fff;
      border-radius: 50%;
    }

    h2 {
      background-color: $primaryColor;
    }

    span {
      color: #666;
      font-size: 14px;
      white-space: nowrap;
      overflow: hidden;
      word-break: break-all;
      text-overflow: ellipsis;
    }
  }

  :deep( .selectCont .pagination ){
    width: 100%!important;
    background: pink;
  }
}
</style>
