<template>
  <div class="app-container">
    <!--    搜索部分-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建者" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="奖项名称" prop="applyName">
      <el-input
        v-model="queryParams.applyName"
        placeholder="请输入奖项名称"
        clearable
        @keyup.enter.native="handleQuery"
      />
    </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <custom-table
      :columns="tableColumns"
      :tableData="noticeList"
      :loading="loading"
      :actions="tableActions"
      :query-params="queryParams"
      :apply-type="applyParam.applyType"
      :modal-type="'score'"
      @handleQuery="handleQuery"
      @resetQuery="resetQuery"
      @handleView="handleView"
      @getList="getList"
      @handleSelectionChange="handleSelectionChange"
    >

    </custom-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 修改查看对话框 -->
    <el-dialog :title="title" :fullscreen="true" center :visible.sync="editOpen" top="0" width="100%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="260px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="是否获得过黄炎培职业教育奖" prop="isReward">
              <el-radio-group :disabled="isReadOnly" v-model="form.isReward">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <Update
                :applyId="applyId"
                :dialog-type="dialogType"
                :table-data="fileData"
                :isShowButton="isShowButton"
                :isShowUploadButton="isShowUploadButton"
                :template-type="templateType"
                ref="childComponent"
              >
                <template v-slot:tableSlot v-if="isView === false">
                  <div v-if="avgScore !== null">
                    平均分:{{avgScore}}
                  </div>
                  <el-table
                    :data="scoreData"
                    style="width: 100%">
                    <el-table-column
                      prop="createBy"
                      label="评分人">
                    </el-table-column>
                    <el-table-column
                      prop="createTime"
                      label="评分时间">
                    </el-table-column>
                    <el-table-column
                      prop="score"
                      label="分数">
                    </el-table-column>
                    <!-- 其他列 -->
                  </el-table>
                </template>
              </Update>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isView === true" >
          <el-col :span="12">
            <el-form-item label="评分" prop="score">
              <el-input
                type="text"
                v-model="form.score"
                placeholder="请进行评分"
                clearable
                oninput="this.value = this.value.replace(/[^\d.]/g, '').replace(/^(\d*\.\d{0,1}).*$/,'$1');"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="isView === true" @click="submitAduit">提交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDetail,
  applyBack, listScore, getScoreInfo, scoreSave
} from "@/api/reward/score";
import CustomTable from "@/components/CustomTable/CustomTable.vue";
import Update from '@/components/AllTypeFile/update.vue'

export default {
  name: "score",
  components: {CustomTable, Update},
  dicts: ['rew_apply_status','rew_teacher_award'],
  data() {
    return {
      scoreData:[],
      avgScore:null,
      templateType:'aduit',
      dialogType: 'edit',
      isShowUploadButton:false,
      //列数据
      tableColumns: [
        {label: '创建者', prop: 'createBy', align: 'center'},
        {label: '奖项名称', prop: 'applyName', align: 'center', showOverflowTooltip: true},
        {label: '状态', prop: 'scoreStatus', align: 'center', slotName: 'scoreStatus'},
        {label: '创建时间', prop: 'createTime', align: 'center'},
        {label: '提交时间', prop: 'appTime', align: 'center', type: 'date'},
        {label: '审核时间', prop: 'authTime', align: 'center', type: 'date'},
      ],
      //操作列
      tableActions: [
        {text: '查看', icon: 'el-icon-view', handler: this.handleView,},
        {text: '评分', icon: 'el-icon-edit', handler: this.handleUpdate,},
      ],
      //文件上传配置项
      fileData:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      noticeList: [],
      isReadOnly: false,
      isShowButton: true,
      isView: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      editOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applyName: undefined,
        applyStatus: '2,4',
        applyType:undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        applyName: [
          {required: true, message: "奖项名称不能为空", trigger: "blur"}
        ],
        isReward: [
          {required: true, message: "请选择", trigger: "change"}
        ],
        score:[
          {required: true, message: "请进行评分", trigger: "blur"}
        ]
      },
      applyParam: {
        applyType: ''
      },
      applyId: '',
      scoreId:null
    };
  },
  created() {

  },
  mounted() {
    this.$store.dispatch('GetInfo').then((res) => {
      let filterData = this.tableActions
      if (res.user.userId === 1){
        let ratingIndex = filterData.findIndex(action => action.text === '评分');
        if (ratingIndex !== -1) {
          // 使用 splice 方法将评分项从数组中删除
          filterData.splice(ratingIndex, 1);
        }
      }
    })
    if (this.$route.path.includes('teacherAward') === true) {
      this.$store.dispatch('apply/setApplyType', {key: 'applyType', value: 'rew_teacher_award'});
      this.applyParam.applyType = this.$store.state.apply.applyType;
      this.queryParams.applyType = this.$store.state.apply.applyType;
    }
    this.getList('mounted');
  },
  methods: {
    /** 查询公告列表 */
    getList(item) {
      this.loading = true;
      let queryObj = {
        pageNum: 1,
        pageSize: 10,
        applyStatus: '2,4',
        applyType: this.applyParam.applyType
      }
      listScore(item === 'mounted' ? queryObj : this.queryParams).then(response => {
        this.noticeList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.fileData = this.dict.type.rew_teacher_award.map(item => {
          return {
            name: item.label,
            fileCode: item.value,
            status: '',
            expanded: false,
            childrenList: []
          };
        })
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.editOpen = false
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        // applyName: undefined,
        isReward: undefined,
        score:undefined
      };
      this.resetForm("form");
      this.scoreData=[]
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 查询参数
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        applyName: undefined,
        applyStatus: '2,4',
        applyType: this.applyParam.applyType
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.applyId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /**查看按钮 */
    handleView(row) {
      this.editOpen = true;
      this.title = "查看申请";
      const applyId = row.applyId || this.ids
      this.isShowButton = false
      this.isReadOnly = true
      this.isView = false
      getDetail(applyId).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.fileData.forEach((item) => {
          item.childrenList = []
        })
        if (response.code === 200) {
          response.data.fileRelationVOList.forEach((item) => {
            let index = this.fileData.findIndex(i => i.fileCode === item.fileCode);
            if (index !== -1) {
              this.fileData[index].childrenList.push({
                name: item.fileName,
                fileName: item.realName,
                url: item.filePath,
                state: item.fileState,
                fileId: item.fileId,
                fileCode: item.fileCode,
              });
            }
          });
        }
        this.getScoreInfo(row)
      });
    },
    getScoreInfo(row){
      getScoreInfo(row.applyId).then((res)=>{
        if (res.data.rewScoreInfos.length > 0){
          this.scoreId = res.data.rewScoreInfos[0].scoreId
          this.form.score = res.data.rewScoreInfos[0].score
          this.scoreData = res.data.rewScoreInfos
        }
        this.avgScore = res.data.avgScore
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isView = true;
      this.applyId = row.applyId
      this.isReadOnly = true
      this.isShowButton = true
      this.isShowUploadButton = false
      const applyId = row.applyId || this.ids
      getDetail(applyId).then(response => {
        this.form.isReward = response.data.isReward;
        this.editOpen = true;
        this.title = "评分";
        this.fileData.forEach((item) => {
          item.childrenList = []
        })
        if (response.code === 200) {
          response.data.fileRelationVOList.forEach((item) => {
            let index = this.fileData.findIndex(i => i.fileCode === item.fileCode);
            if (index !== -1) {
              this.fileData[index].childrenList.push({
                name: item.fileName,
                fileName: item.realName,
                url: item.filePath,
                state: item.fileState,
                fileId: item.fileId,
                fileCode: item.fileCode,
              });
            }

          });
        }
        this.getScoreInfo(row)
      });
    },
    submitAduit(){
      let saveParams = {
        applyId: this.applyId,
        score: this.form.score,
        scoreId: this.scoreId
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          scoreSave(saveParams).then(response => {
            this.$modal.msgSuccess("提交成功");
            this.editOpen = false
            this.getList();
          });
        }
      });
      // scoreSave().then(resp => {
      //   if (resp.code === 200){
      //     this.$modal.msgSuccess(res.msg)
      //     this.editOpen = false
      //     this.getList('mounted')
      //   }
      // })
    },
    callback(){
      this.$prompt('请输入退回意见', '退回意见', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        customClass: 'custom-prompt'
      }).then(({ value }) => {
        applyBack(this.applyId, value).then(res => {
          if (res.code === 200){
            this.$modal.msgSuccess(res.msg)
            this.editOpen = false
            this.getList('mounted')
          }else{
            this.$modal.msgSuccess(res.msg)
          }
        })
      }).catch(() => {

      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const applyId = row.applyId || this.ids
      this.$modal.confirm('是否确认删除申请?').then(function () {
        return delApply(applyId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        localStorage.removeItem('applyId');
      }).catch(() => {
      });
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .el-dialog--center .el-dialog__body {
  padding-bottom: 0;
}

::v-deep .el-dialog__footer {
  padding: 0;
}

.fullscreen-dialog {
  .el-dialog__wrapper {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
    background-color: rgba(0, 0, 0, 0.5); /* 遮罩层透明度 */
  }

  .el-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    border: none;
    border-radius: 0;
  }
}
</style>