<template>

  <div class="customer-css">

    <!-- 查询条件 -->

    <el-form :inline="true" label-position="top" class="pi-search-form">

      <el-form-item label="任务单号">

        <el-input v-model="searchData.requestNo" style="width:140px" @keyup.enter.native="getList" />

      </el-form-item>

      <el-form-item>

        <span style="cursor: pointer" slot="label" @click="getBaseList(501)"><a href="#">供应商编码</a></span>

        <el-input v-model="searchData.supplierNo" style="width: 130px"></el-input>

      </el-form-item>

      <el-form-item label="供应商名称">

        <el-input v-model="searchData.supplierName" style="width:200px" @keyup.enter.native="getList" />

      </el-form-item>

      <el-form-item label="创建者">

        <el-input v-model="searchData.createBy" style="width:140px" @keyup.enter.native="getList" />

      </el-form-item>

      <el-form-item label="预计完成时间">

        <el-date-picker v-model="searchData.wantedCompleteDateStart" type="date" placeholder="Start Date"

                        value-format="yyyy-MM-dd"

                        style="width:140px" />

        -

        <el-date-picker v-model="searchData.wantedCompleteDateEnd" type="date" placeholder="End Date"

                        value-format="yyyy-MM-dd"

                        style="width:140px" />

      </el-form-item>

      <el-form-item label="创建时间">

        <el-date-picker v-model="searchData.createDateStart" type="date" placeholder="Start Date"

                        value-format="yyyy-MM-dd HH:mm:ss"

                        style="width:140px" />

        -

        <el-date-picker v-model="searchData.createDateEnd" type="date" placeholder="End Date"

                        value-format="yyyy-MM-dd HH:mm:ss"

                        style="width:140px" />

      </el-form-item>

      <el-form-item label="状态">

        <el-select v-model="searchData.statusList" multiple collapse-tags clearable style="width:150px" placeholder="All">

          <el-option

            v-for="item in reviewStatusOptions"

            :key="item.value"

            :label="item.label"

            :value="item.value" />

        </el-select>

      </el-form-item>

      <el-form-item label=" ">

        <el-button type="primary" class="customer-bun-min" @click="getList">查询</el-button>

      </el-form-item>

    </el-form>



    <!-- 列表 -->

    <el-table :data="dataList" :height="requestTableHeight - 100" border highlight-current-row v-loading="loading"

              @row-click="rowClick" @current-change="handleMainCurrentChange" ref="mainTable" style="width:100%;margin-bottom:8px">

      <el-table-column fixed="right" label="操作" width="80" header-align="center" align="center">

        <template slot-scope="scope">

          <a v-if="canOperate(scope.row)" class="customer-a" @click.stop="openReviewDialog(scope.row)">审核</a>

        </template>

      </el-table-column>

      <el-table-column prop="requestNo" label="任务单号" min-width="120" header-align="center" align="left" />

      <el-table-column prop="supplierNo" label="供应商编码" width="120" header-align="center" align="left" />

      <el-table-column prop="supplierName" label="供应商名称" min-width="200" header-align="center" align="left" show-overflow-tooltip />

      <el-table-column prop="wantedCompleteDate" label="预计完成时间" width="160" header-align="center" align="center" />

      <el-table-column prop="status" label="状态" width="90" header-align="center" align="center" />

      <el-table-column prop="reviewBy" label="审核人" min-width="90" header-align="center" align="left" />

      <el-table-column prop="reviewDate" label="审核时间" width="130" header-align="center" align="center" />

      <el-table-column prop="approveBy" label="批准人" min-width="90" header-align="center" align="left" />

      <el-table-column prop="approveDate" label="批准时间" width="130" header-align="center" align="center" />

      <el-table-column prop="comments" label="备注" min-width="160" header-align="center" align="left" />

      <el-table-column prop="createBy" label="创建者" min-width="100" header-align="center" align="left" />

      <el-table-column prop="createDate" label="创建时间" width="130" header-align="center" align="center" />

    </el-table>



    <el-pagination style="margin-top:0" @size-change="sizeChangeHandle" @current-change="currentChangeHandle"

      :current-page="pageIndex" :page-sizes="[20,50,100,200,500]" :page-size="pageSize" :total="totalPage"

      layout="total, sizes, prev, pager, next, jumper" />



    <!-- 指标 + Progress -->

    <el-row :gutter="10" style="margin-top:12px">

      <el-col :span="16">

        <div class="sub-panel-header">

          <span style="font-size:16px">考核单</span>

        </div>

        <el-table :data="indicatorList" size="mini" border :height="indicatorTableHeight" highlight-current-row

                  ref="indicatorTable" v-loading="indicatorLoading" @row-click="selectIndicatorRow">

          <el-table-column prop="indicatorCode" label="指标代码" min-width="120" header-align="center" align="left" show-overflow-tooltip />

          <el-table-column prop="indicatorDesc" label="指标描述" min-width="220" header-align="center" align="left" show-overflow-tooltip />

          <el-table-column prop="category" label="指标分类" width="110" header-align="center" align="center" />

          <el-table-column prop="ownerRole" label="负责部门" width="110" header-align="center" align="center" />

          <el-table-column prop="maxScore" label="最高分" width="110" header-align="center" align="right" />

          <el-table-column prop="score" label="分数" width="90" header-align="center" align="right" />

        </el-table>

      </el-col>

      <el-col :span="8">

        <div class="sub-panel-header">

          <span style="font-size:16px">进度 <span v-if="viewIndicatorCode"></span></span>

        </div>

        <el-table :data="progressList" size="mini" border :height="indicatorTableHeight" v-loading="progressLoading">

          <el-table-column prop="departmentName" label="部门" min-width="90" header-align="center"

                           align="left" />

          <el-table-column prop="owner" label="负责人" min-width="80" header-align="center" align="left" />

          <el-table-column prop="userDisplay" label="负责人名称" min-width="90" header-align="center" align="left" />

          <el-table-column prop="completedFlag" label="已完成" width="60" header-align="center" align="center">

          </el-table-column>

          <el-table-column prop="completedDate" label="完成时间" min-width="140" header-align="center"

                           align="center" />

        </el-table>

      </el-col>

    </el-row>



    <!-- Review 弹窗 -->

    <el-dialog title="审核" :visible.sync="reviewDialogVisible" width="374px" top="8vh" :close-on-click-modal="false"

               v-drag>

      <el-form :inline="true" label-position="top" class="create-top-form">

        <el-form-item

          label="任务单号"><el-input v-model="reviewForm.requestNo" disabled style="width: 120px"/></el-form-item>

        <el-form-item label="审核人"><el-input v-model="reviewForm.createBy" disabled style="width: 120px"/></el-form-item>

      </el-form>

      <el-form :inline="true" label-position="top" size="mini" class="create-top-form">

        <el-form-item label="供应商编号"><el-input v-model="reviewForm.supplierNo" disabled style="width: 120px"/></el-form-item>

        <el-form-item label="供应商名称"><el-input v-model="reviewForm.supplierName" disabled

                                                      style="width: 210px"/></el-form-item>

      </el-form>

      <el-form :inline="true" label-position="top" size="mini" class="create-top-form">

        <el-form-item label="备注" :required="true">

          <el-input type="textarea" :rows="2" v-model="reviewForm.comments" style="width: 343px" />

        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">

        <el-button type="primary" :loading="reviewSaving" @click="saveReview">审核</el-button>

        <el-button type="danger" :loading="voidSaving" @click="voidReview">作废</el-button>

        <el-button @click="reviewDialogVisible=false">取消</el-button>

      </span>

    </el-dialog>

    <Chooselist ref="baseList" @getBaseData="getBaseData"></Chooselist>

  </div>

</template>



<script>

import { searchEvaluateRequestList, getEvaluateRequestIndicators, getEvaluateRequestIndicatorProgress } from '@/api/supplierPerformance/myPerformanceEvaluateRequest.js'

import { updateEvaluateRequestReviewOrApprove } from '@/api/supplierPerformance/myPerformanceEvaluateRequest'

import {

  PERF_REVIEW_STATUS_OPTIONS,

  PERF_REVIEW_STATUS_DEFAULT

} from './supplierPerformanceStatusOptions.js'

import Chooselist from '@/views/modules/common/Chooselist_eam'

export default {

  components: {

    Chooselist,

  },

  name: 'PerformanceEvaluateRequestReview',

  data() {

    return {

      height: 500,

      loading: false,

      dataList: [],

      pageIndex: 1,

      pageSize: 20,

      totalPage: 0,

      reviewStatusOptions: PERF_REVIEW_STATUS_OPTIONS,

      searchData: {

        site: this.$store.state.user.site,

        username: this.$store.state.user.name,

        requestNo: '',

        supplierNo: '',

        supplierName: '',

        createBy: '',

        wantedCompleteDateStart: '',

        wantedCompleteDateEnd: '',

        createDateStart: '',

        createDateEnd: '',

        statusList: ['已完成']

      },

      currentRequest: {},

      indicatorList: [],

      indicatorLoading: false,

      reviewDialogVisible: false,

      reviewSaving: false,

      voidSaving: false,

      reviewForm: { id:'', requestNo:'', supplierNo:'', supplierName:'', createBy:'', comments:'' },

      viewIndicatorCode: '',

      progressList: [],

      progressLoading: false,

      progressRequestKey: '',

    }

  },

  computed: {

    requestTableHeight() { return this.height - 360 < 260 ? 260 : this.height - 360 },

    indicatorTableHeight() { return 300 }

  },

  mounted() { this.calcHeight(); window.addEventListener('resize', this.calcHeight); this.getList() },

  beforeDestroy() { window.removeEventListener('resize', this.calcHeight) },

  methods: {

    getBaseList (val) {

      this.tagNo = val

      this.$nextTick(() => {

        let strVal = ''

        let conSql = ''

        if (val === 501) {

          strVal = this.searchData.supplierNo || ''

          conSql = " and site = '" + this.$store.state.user.site + "'"

        }

        this.$refs.baseList.init(val, strVal, conSql)

      })

    },

    getBaseData (val) {

      if (this.tagNo === 501) {

        const supplierNoVal = val.SupplierID || val.supplierID || val.supplierId || ''

        this.searchData.supplierNo = supplierNoVal

      }

    },

    calcHeight() { this.$nextTick(()=> { this.height = window.innerHeight - 40 }) },

    clearSubDetails() {

      this.currentRequest = {}

      this.indicatorList = []

      this.viewIndicatorCode = ''

      this.progressList = []

      this.progressRequestKey = ''

      this.$nextTick(() => {

        if (this.$refs.mainTable) this.$refs.mainTable.setCurrentRow(null)

        if (this.$refs.indicatorTable) this.$refs.indicatorTable.setCurrentRow(null)

      })

    },

    getList() {

      this.loading = true

      if (this.searchData.statusList.length === 0) this.searchData.statusList = [...PERF_REVIEW_STATUS_DEFAULT]

      const params = { ...this.searchData, statusList: this.searchData.statusList , page: this.pageIndex, limit: this.pageSize, selectType: 1 }

      searchEvaluateRequestList(params).then(({data})=> {

        if (data && (data.code===0||data.code==='0')) {

          if (data.page) {

            this.dataList = data.page.list || []

            this.pageIndex = data.page.currPage || params.page

            this.pageSize = data.page.pageSize || params.limit

            this.totalPage = data.page.totalCount || 0

            if (this.dataList.length > 0) {

              this.$nextTick(() => {

                this.$refs.mainTable.setCurrentRow(this.dataList[0])

                this.rowClick(this.dataList[0])

              })

            } else {

              this.clearSubDetails()

            }

          } else {

            this.dataList = data.rows || []

            this.totalPage = data.total || this.dataList.length

            if (this.dataList.length === 0) this.clearSubDetails()

          }

        } else {

          this.dataList = []

          this.totalPage = 0

          this.clearSubDetails()

        }

      }).catch(() => {

        this.dataList = []

        this.totalPage = 0

        this.clearSubDetails()

      })

        .finally(()=> { this.loading=false })

    },

    sizeChangeHandle(v){ this.pageSize=v; this.pageIndex=1; this.getList() },

    currentChangeHandle(v){ this.pageIndex=v; this.getList() },

    handleMainCurrentChange(row) {

      if (!row) this.clearSubDetails()

    },

    rowClick(row) {

      if (!row) {

        this.clearSubDetails()

        return

      }

      this.currentRequest = row

      this.viewIndicatorCode = ''

      this.progressList = []

      this.loadIndicators()

    },

    loadIndicators() {

      if (!this.currentRequest.requestNo) {

        this.indicatorList = []

        this.viewIndicatorCode = ''

        this.progressList = []

        return

      }

      this.indicatorLoading = true

      this.indicatorList = []

      this.viewIndicatorCode = ''

      this.progressList = []

      const p = { requestId: this.currentRequest.id, requestNo: this.currentRequest.requestNo, site: this.$store.state.user.site }

      getEvaluateRequestIndicators(p).then(({ data }) => {

        if (data && (data.code === 0 || data.code === '0')) {

          this.indicatorList = data.list || []

          this.$nextTick(() => {

            if (this.indicatorList.length > 0) {

              this.$refs.indicatorTable.setCurrentRow(this.indicatorList[0])

              this.selectIndicatorRow(this.indicatorList[0])

            } else {

              this.viewIndicatorCode = ''

              this.progressList = []

              this.$refs.indicatorTable && this.$refs.indicatorTable.setCurrentRow(null)

            }

          })

        } else {

          this.indicatorList = []

          this.viewIndicatorCode = ''

          this.progressList = []

        }

      }).catch(() => {

        this.indicatorList = []

        this.viewIndicatorCode = ''

        this.progressList = []

      }).finally(() => { this.indicatorLoading = false })

    },

    selectIndicatorRow(row) {

      if (!row) {

        this.viewIndicatorCode = ''

        this.progressList = []

        return

      }

      this.viewIndicatorCode = row.indicatorCode

      this.progressList = []

      this.loadProgress()

    },

    loadProgress() {

      if (!this.viewIndicatorCode || !this.currentRequest.requestNo) {

        this.progressList = []

        return

      }

      const requestKey = `${this.currentRequest.id || ''}_${this.currentRequest.requestNo}_${this.viewIndicatorCode}`

      this.progressRequestKey = requestKey

      this.progressLoading = true

      const p = { requestId: this.currentRequest.id, requestNo: this.currentRequest.requestNo, site: this.$store.state.user.site }

      getEvaluateRequestIndicatorProgress(p).then(({ data }) => {

        if (this.progressRequestKey !== requestKey) return

        if (data && (data.code === 0 || data.code === '0')) {

          this.progressList = data.list || []

        } else {

          this.progressList = []

        }

      }).catch(() => {

        if (this.progressRequestKey !== requestKey) return

        this.progressList = []

      }).finally(() => { this.progressLoading = false })

    },

    canOperate(row){

      if(!row) return false;

      const s=(row.status||'').trim();

      return s==='已完成';

    },

    openReviewDialog(row){

      this.reviewForm = { id:row.id, requestNo:row.requestNo, supplierNo:row.supplierNo, supplierName:row.supplierName, createBy:row.createBy, comments: row.reviewComments || '' }

      this.reviewDialogVisible = true

    },

    saveReview(){

      if (this.reviewSaving || this.voidSaving) return

      const c = (this.reviewForm.comments||'').trim()

      if(!c){ this.$message.warning('Comments不能为空'); return }

      this.reviewSaving = true

      const payload = { site:this.$store.state.user.site, id:this.reviewForm.id, requestNo:this.reviewForm.requestNo,

        comments:c, updateBy:this.$store.state.user.name, updateType: 1 }

      updateEvaluateRequestReviewOrApprove(payload).then(({data})=> {

        if (data && (data.code===0||data.code==='0')) { this.$message.success('审核成功'); this.reviewDialogVisible=false; this.getList() } else { this.$message.error((data&&data.msg)||'审核失败') }

      }).catch(e=> this.$message.error('审核失败: '+ e.message)).finally(()=> { this.reviewSaving=false })

    },

    voidReview() {

      if (this.reviewSaving || this.voidSaving) return

      this.$confirm('是否作废该绩效审核单？', '提示', { type: 'warning' }).then(() => {

        this.voidSaving = true

        const payload = {

          site: this.$store.state.user.site,

          id: this.reviewForm.id,

          requestNo: this.reviewForm.requestNo,

          updateBy: this.$store.state.user.name,

          updateType: 4

        }

        updateEvaluateRequestReviewOrApprove(payload).then(({ data }) => {

          if (data && (data.code === 0 || data.code === '0')) {

            this.$message.success('作废成功')

            this.reviewDialogVisible = false

            this.getList()

          } else {

            this.$message.error((data && data.msg) || '作废失败')

          }

        }).catch(e => this.$message.error('作废失败: ' + e.message)).finally(() => { this.voidSaving = false })

      }).catch(() => {})

    }

  }

}

</script>



<style scoped>

.pi-search-form { margin-top:0; }

.sub-panel-header { display:flex; align-items:center; justify-content:space-between; font-weight:600; padding:4px 6px; background:#f5f7fa; border:1px solid #ebeef5; border-bottom:none; }

</style>


