<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 taskStatusOptions"
            :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-button type="primary" class="customer-bun-min" @click="openCreateDialog">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- Evaluate Request 列表 -->
    <el-table :data="dataList" :height="requestTableHeight - 100" border highlight-current-row v-loading="loading"
              @row-click="rowClick" ref="mainTable" style="width:100%;margin-bottom:8px">
      <el-table-column prop="requestNo" label="任务单号" min-width="140" 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="110" header-align="center" align="center" />
      <el-table-column prop="createBy" label="创建者" min-width="90" header-align="center" align="left"  />
      <el-table-column prop="createDate" label="创建时间" width="140" header-align="center" align="center" />
      <el-table-column fixed="right" label="操作" width="160" header-align="center" align="center">
        <template slot-scope="scope">
          <template v-if="!isCompleted(scope.row)">
            <a class="customer-a" @click.stop="openEditDialog(scope.row)">编辑</a>
            <span style="color:#dcdfe6;margin:0 2px">|</span>
            <a class="customer-a" @click.stop="removeRequest(scope.row)">删除</a>
          </template>
        </template>
      </el-table-column>
    </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" />

    <!-- 指标 & 进度 查看 -->
    <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" @row-click="selectIndicatorRow" v-loading="indicatorLoading">
          <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>
          <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>

    <!-- 调整供应商等级 -->
    <el-dialog title="调整供应商等级" :visible.sync="adjustVisible" width="420px" :close-on-click-modal="false" v-drag>
      <el-form label-position="top" size="small">
        <el-form-item label="任务单号">
          <el-input v-model="currentRequest.requestNo" disabled />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="currentRequest.supplierName" disabled />
        </el-form-item>
        <el-form-item label="新等级" :required="true">
          <el-select v-model="adjustForm.newLevel" placeholder="Select" style="width:180px">
            <el-option v-for="l in supplierLevelOptions" :key="l.value" :label="l.label" :value="l.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="adjustForm.remark" :rows="3" maxlength="300" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="adjustLoading" @click="submitAdjust">确认</el-button>
        <el-button @click="adjustVisible=false">取消</el-button>
      </span>
    </el-dialog>

    <!-- 新建 / 编辑 绩效请求弹窗 -->
    <el-dialog :title="isEdit ? '编辑绩效评估考核' : '新增绩效评估考核'" :visible.sync="createDialogVisible" :width="isEdit ? '760px' : '940px'" top="4vh"
               :close-on-click-modal="false" v-drag>
      <el-form :inline="true" label-position="top" size="mini" class="create-top-form">
        <el-form-item :required="true">
          <span slot="label" @click="getBaseList(2014)"><a href="#">模板编号</a></span>
          <!-- 允许编辑模式下修改模板号: 去掉 :disabled="isEdit" -->
          <el-input v-model="createForm.templateNo" style="width:150px" @blur="autoFetchTemplateInfo" />
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input v-model="createForm.templateDesc" style="width:260px" disabled />
        </el-form-item>
        <el-form-item label="预计完成时间" :required="true">
          <el-date-picker v-model="createForm.wantedCompleteDate" type="date" value-format="yyyy-MM-dd" style="width:160px" />
        </el-form-item>
        <el-form-item label=" " style="margin-top:-2px" v-if="!isEdit">
          <el-button size="small" type="primary" :disabled="!createForm.templateNo" @click="openTemplateIndicatorDialog">指标信息</el-button>
        </el-form-item>
        <el-form-item v-if="isEdit" label="任务单号">
          <el-input v-model="createForm.requestNo" disabled style="width:150px" />
        </el-form-item>
        <el-form-item label=" " style="margin-top:-2px" v-if="isEdit">
          <el-button size="small" type="primary" :disabled="!createForm.templateNo" @click="openTemplateIndicatorDialog">指标信息</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" style="margin-top:5px">
        <el-col :span="12" v-if="!isEdit">
          <!-- Supplier List (only new) -->
          <div class="sub-panel-header supplier-panel-header">
            <span class="sub-panel-title">供应商清单</span>
            <div class="supplier-header-filters">
              <el-input
                v-model="supplierQuery.supplierNo"
                size="mini"
                placeholder="供应商编码"
                clearable
                style="width:100px"
                @keyup.enter.native="loadSuppliers"
              />
              <el-input
                v-model="supplierQuery.supplierName"
                size="mini"
                placeholder="供应商名称"
                clearable
                style="width:200px"
                @keyup.enter.native="loadSuppliers"
              />
              <el-button size="mini" type="primary" @click="loadSuppliers">查询</el-button>
            </div>
          </div>
          <el-table ref="createSupplierTable" :data="supplierList" size="mini" border height="380" v-loading="supplierLoading" @selection-change="supplierSelectionChange">
            <el-table-column type="selection" width="40" header-align="center" align="center" />
            <el-table-column prop="supplierNo" label="供应商编码" width="120" header-align="center" align="left" />
            <el-table-column prop="supplierName" label="供应商名称" min-width="180" header-align="center" align="left" show-overflow-tooltip />
          </el-table>
        </el-col>
        <el-col :span="12" v-if="!isEdit">
          <!-- Specify Owner (new) -->
          <div class="sub-panel-header">
            <span style="font-size:14px">指定负责人</span>
          </div>
          <el-table :data="departmentList" :key="'dept-new'" size="mini" border height="380" v-loading="deptLoading">
            <el-table-column prop="departmentNo" label="部门编号" min-width="60" header-align="center" align="left" />
            <el-table-column prop="departmentName" label="部门名称" min-width="80" header-align="center" align="left" />
            <el-table-column prop="owner" label="负责人" min-width="80" header-align="center" align="left" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="scope.row.owner">{{ scope.row.owner }}</span>
                <span v-else style="color:#999">(未选择)</span>
              </template>
            </el-table-column>
            <el-table-column prop="ownerDisplay" label="负责人姓名" min-width="120" header-align="center" align="left" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="scope.row.ownerDisplay">{{ scope.row.ownerDisplay }}</span>
                <span v-else style="color:#999">-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="90" header-align="center" align="center">
              <template slot-scope="scope">
                <a class="customer-a" @click="openOwnerSelect(scope.row)">查询</a>
                <a v-if="scope.row.owner" class="customer-a" style="margin-left:4px" @click="clearOwner(scope.row)">清除</a>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24" v-if="isEdit">
          <!-- Owner only (edit) -->
          <div class="sub-panel-header">
            <span style="font-size:14px">指定负责人</span>
          </div>
          <el-table :data="departmentList" :key="'dept-edit'" size="mini" border height="380" v-loading="deptLoading">
            <el-table-column prop="departmentNo" label="部门编号" min-width="100" header-align="center" align="left" />
            <el-table-column prop="departmentName" label="部门名称" min-width="200" header-align="center" align="left" />
            <el-table-column prop="owner" label="负责人" min-width="120" header-align="center" align="left" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="scope.row.owner">{{ scope.row.owner }}</span>
                <span v-else style="color:#999">(未选择)</span>
              </template>
            </el-table-column>
            <el-table-column prop="ownerDisplay" label="负责人姓名" min-width="140" header-align="center" align="left" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="scope.row.ownerDisplay">{{ scope.row.ownerDisplay }}</span>
                <span v-else style="color:#999">-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="110" header-align="center" align="center">
              <template slot-scope="scope">
                <a class="customer-a" @click="openOwnerSelect(scope.row)">查询</a>
                <a v-if="scope.row.owner" class="customer-a" style="margin-left:4px" @click="clearOwner(scope.row)">清除</a>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="createSaving" @click="saveCreate">保存</el-button>
        <el-button @click="createDialogVisible=false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 模板指标弹窗 -->
    <el-dialog title="指标信息" :visible.sync="templateIndicatorDialogVisible" width="760px" top="8vh" :close-on-click-modal="false" v-drag>
      <div style="margin-bottom:6px;font-size:12px;color:#666">Template: {{createForm.templateNo}} - {{createForm.templateDesc}}</div>
      <el-table :data="templateIndicatorList" size="mini" border height="420" v-loading="templateIndicatorLoading">
        <el-table-column prop="indicatorCode" label="指标编号" min-width="140" header-align="center" align="left" />
        <el-table-column prop="indicatorDesc" label="指标描述" min-width="240" header-align="center" align="left" show-overflow-tooltip />
        <el-table-column prop="category" label="指标分类" width="120" header-align="center" align="center" />
        <el-table-column prop="ownerRole" label="负责部门" width="120" header-align="center" align="center" />
      </el-table>
      <span slot="footer" class="dialog-footer"><el-button @click="templateIndicatorDialogVisible=false">关闭</el-button></span>
    </el-dialog>

    <!-- Owner 选择弹窗 -->
    <el-dialog title="Select Owner" :visible.sync="ownerDialogVisible" width="600px" top="10vh" :close-on-click-modal="false" v-drag>
      <div style="margin-bottom:4px;font-size:12px;color:#555">Department: {{ currentDeptRow.departmentName }}</div>
      <el-table :data="ownerUserList" size="mini" border height="360" highlight-current-row v-loading="ownerLoading" @row-dblclick="confirmOwner">
        <el-table-column prop="username" label="用户名称" width="160" header-align="center" align="left" />
        <el-table-column prop="userDisplay" label="用户显示名" min-width="260" header-align="center" align="left" show-overflow-tooltip />
      </el-table>
      <span slot="footer" class="dialog-footer"><el-button @click="ownerDialogVisible=false">关闭</el-button></span>
    </el-dialog>
    <Chooselist ref="baseList"  @getBaseData="getBaseData"></Chooselist>
  </div>
</template>

<script>
import {
  adjustSupplierLevel,
  deleteEvaluateRequest,
  getEvaluateRequestIndicatorProgress,
  getEvaluateRequestIndicators,
  searchEvaluateRequestList,
  updateEvaluateRequest
} from '@/api/supplierPerformance/myPerformanceEvaluateRequest.js'
import {
  fetchDepartmentList,
  fetchOwnerUserList,
  fetchSupplierList,
  fetchTemplateInfo,
  saveEvaluateRequest
} from '@/api/supplierPerformance/performanceEvaluateRequestBuild.js'
import Chooselist from '@/views/modules/common/Chooselist_eam'
import {getTemplateIndicators} from "../../../api/supplierPerformance/performanceIndicatorTemplate";
import {
  PERF_TASK_STATUS_OPTIONS,
  PERF_TASK_STATUS_DEFAULT
} from './supplierPerformanceStatusOptions.js'

export default {
  components: {
    Chooselist,
  },
  name: 'MyPerformanceEvaluateRequest',
  data() {
    return {
      height: 500,
      loading: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      taskStatusOptions: PERF_TASK_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,
      viewIndicatorCode: '',
      // progress
      progressList: [],
      progressLoading: false,
      // 调整等级
      adjustVisible: false,
      adjustLoading: false,
      adjustForm: { newLevel: '', remark: '' },
      supplierLevelOptions: [ {label:'A',value:'A'},{label:'B',value:'B'},{label:'C',value:'C'},{label:'D',value:'D'} ],
      // 新建弹窗相关
      createDialogVisible: false,
      createForm: { templateNo:'', templateDesc:'', wantedCompleteDate:'' },
      createSaving: false,
      templateIndicatorDialogVisible: false,
      templateIndicatorList: [],
      templateIndicatorLoading: false,
      supplierQuery: { supplierNo: '', supplierName: '' },
      supplierList: [],
      supplierSelected: [],
      supplierLoading: false,
      departmentList: [],
      deptLoading: false,
      ownerDialogVisible: false,
      ownerUserList: [],
      ownerLoading: false,
      ownerQuery: { keyword:'' },
      currentDeptRow: {},
      isEdit: false,
    }
  },
  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: {
    // 获取基础数据列表S
    getBaseList (val,type) {
      this.tagNo = val
      this.$nextTick(() => {
        let strVal = ''
        let conSql = ''
        if (val === 2014 ) {
          strVal = this.createForm.templateNo
          conSql = " and  site = '"  + this.$store.state.user.site + "'"
        } else if (val === 501) {
          strVal = this.searchData.supplierNo || ''
          conSql = " and site = '" + this.$store.state.user.site + "'"
        }
        this.$refs.baseList.init(val, strVal,conSql)
      })
    },
    /* 列表方法的回调 */
    getBaseData (val) {
      console.log('Chooselist返回的数据:', val, 'tagNo:', this.tagNo)
      if (this.tagNo === 2014) {
        this.createForm.templateId = val.id
        this.createForm.templateNo = val.template_no
        this.createForm.templateDesc = val.template_desc
        this.loadDepartments()
      } else if (this.tagNo === 501) {
        // 供应商编码字段 - SQL返回: SupplierID, SupplierName
        const supplierNoVal = val.SupplierID || val.supplierID || val.supplierId || ''
        this.searchData.supplierNo = supplierNoVal
        console.log('供应商编码赋值:', supplierNoVal)
      }
    },
    calcHeight() { this.$nextTick(()=> { this.height = window.innerHeight - 40 }) },
    getList() {
      this.loading = true
      if (this.searchData.statusList.length === 0) this.searchData.statusList = [...PERF_TASK_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.dataList = data.rows || []
            this.totalPage = data.total || this.dataList.length
          }
        } else { this.dataList=[]; this.totalPage=0 }
      }).catch(()=> { this.dataList=[]; this.totalPage=0 })
        .finally(()=> { this.loading=false })
    },
    sizeChangeHandle(v) { this.pageSize=v; this.pageIndex=1; this.getList() },
    currentChangeHandle(v) { this.pageIndex=v; this.getList() },
    rowClick(row) { this.currentRequest = row; this.loadIndicators() },
    loadIndicators() {
      if (!this.currentRequest.requestNo) { this.indicatorList=[]; return }
      this.indicatorLoading = true
      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=[] } })
        } else { this.indicatorList=[] }
      }).catch(()=> { this.indicatorList=[] })
        .finally(()=> { this.indicatorLoading=false })
    },
    selectIndicatorRow(row) { this.viewIndicatorCode = row.indicatorCode; this.loadProgress() },
    loadProgress() {
      if (!this.viewIndicatorCode || !this.currentRequest.requestNo) { this.progressList=[]; return }
      this.progressLoading = true
      const p = { requestId: this.currentRequest.id, requestNo: this.currentRequest.requestNo, site: this.$store.state.user.site }
      getEvaluateRequestIndicatorProgress(p).then(({data}) => {
        if (data && (data.code === 0 || data.code === '0')) {
          this.progressList = data.list
        } else { this.progressList=[] }
      }).catch(()=> { this.progressList=[] })
        .finally(()=> { this.progressLoading=false })
    },
    openAdjustDialog(row) { this.currentRequest = row; this.adjustForm = { newLevel:'', remark:'' }; this.adjustVisible=true },
    submitAdjust() {
      if (!this.adjustForm.newLevel) { this.$message.warning('请选择等级'); return }
      this.adjustLoading = true
      const payload = { requestId: this.currentRequest.id, requestNo: this.currentRequest.requestNo, supplierCode: this.currentRequest.supplierCode, newLevel: this.adjustForm.newLevel, remark: this.adjustForm.remark, site: this.$store.state.user.site, user: this.$store.state.user.name }
      adjustSupplierLevel(payload).then(({data}) => {
        if (data && (data.code===0 || data.code==='0')) { this.$message.success('调整成功'); this.adjustVisible=false; this.getList() } else { this.$message.error((data&&data.msg)||'调整失败') }
      }).catch(e=> this.$message.error('调整失败: '+ e.message))
        .finally(()=> { this.adjustLoading=false })
    },
    openEditDialog(row) {
      this.isEdit = true
      this.createSaving = false
      this.currentRequest = row
      this.createForm = {
        templateNo: row.templateNo,
        templateDesc: row.templateDesc,
        wantedCompleteDate: row.wantedCompleteDate,
        id: row.id,
        requestNo: row.requestNo,
        templateId: row.templateId,
        _originalTemplateNo: row.templateNo // 记录原模板号用于校验
      }
      this.createDialogVisible = true
      this.deptLoading = true
      this.loadDepartments()
      // 载入指标用于后续 score 校验
      this.loadIndicators()
    },
    reloadEditOwners() { if (!this.isEdit || !this.createForm.id) return; this.openEditDialog({ templateNo:this.createForm.templateNo, wantedCompleteDate:this.createForm.wantedCompleteDate, id:this.createForm.id, requestNo:this.createForm.requestNo }) },
    removeRequest(row) {
      const site = this.$store.state.user.site
      // 先获取该请求的指标，若存在已评分(score>0)则禁止删除
      getEvaluateRequestIndicators({ requestId: row.id, requestNo: row.requestNo, site }).then(({data}) => {
        let indicators = []
        if (data && (data.code === 0 || data.code === '0')) {
          indicators = data.list || data.rows || data.obj || []
        }
        const hasScored = indicators.some(i => Number(i.score) > 0)
        if (hasScored) {
          this.$message.error('该考核任务存在已评分指标，禁止删除')
          return
        }
        this.$confirm('确认删除该考核任务: ' + row.requestNo + ' ?', '提示', { type: 'warning' }).then(() => {
          deleteEvaluateRequest({ id: row.id, site }).then(({data: delData}) => {
            if (delData && (delData.code === 0 || delData.code === '0')) { this.$message.success('删除成功'); this.getList() }
            else { this.$message.error((delData && delData.msg) || '删除失败') }
          }).catch(e => this.$message.error('删除失败: ' + e.message))
        }).catch(()=>{})
      }).catch(e => {
        this.$message.error('校验失败: ' + e.message)
      })
    },
    saveCreate() {
      if (!this.validateCreate()) return
      this.createSaving = true
      const site = this.$store.state.user.site
      if (this.isEdit) {
        const payload = {
          site,
          id: this.createForm.id,
          requestNo: this.createForm.requestNo,
          templateNo: this.createForm.templateNo,
          wantedCompleteDate: this.createForm.wantedCompleteDate,
          detailList: this.departmentList.map(d=> ({ department: d.departmentNo || d.department || d.departmentName, owner: d.owner })),
          updateBy: this.$store.state.user.name
        }
        updateEvaluateRequest(payload).then(({data})=> {
          if (data && (data.code===0||data.code==='0')) { this.$message.success('更新成功'); this.createDialogVisible=false; this.isEdit=false; this.getList() }
          else { this.$message.error((data&&data.msg)||'更新失败') }
        }).catch(e=> this.$message.error('更新失败: '+ e.message))
          .finally(()=> { this.createSaving=false })
      } else {
        const payload = {
          site,
          templateNo: this.createForm.templateNo,
          wantedCompleteDate: this.createForm.wantedCompleteDate,
          headerList: this.supplierSelected.map(s=> ({ supplierNo:s.supplierNo, supplierName:s.supplierName })),
          detailList: this.departmentList.map(d=> ({ department: d.departmentNo || d.department || d.departmentName, owner: d.owner })),
          createBy: this.$store.state.user.name
        }
        saveEvaluateRequest(payload).then(({data})=> {
          if (data && (data.code===0||data.code==='0')) { this.$message.success('保存成功'); this.createDialogVisible=false; this.getList() } else { this.$message.error((data&&data.msg)||'保存失败') }
        }).catch(e=> this.$message.error('保存失败: '+ e.message))
          .finally(()=> { this.createSaving=false })
      }
    },
    openCreateDialog() {
      this.isEdit = false
      this.resetCreateForm();
      this.createDialogVisible = true;
      this.supplierList = [];
      this.departmentList = [];
    },
    resetCreateForm() {
      this.createForm = { templateNo:'', templateDesc:'', wantedCompleteDate:'' };
      this.templateIndicatorList = [];
      this.supplierSelected = [];
      this.supplierQuery = { supplierNo: '', supplierName: '' };
      this.supplierList = [];
      if (this.$refs.createSupplierTable) this.$refs.createSupplierTable.clearSelection();
      this.departmentList.forEach(d=>{ d.owner=''; });
    },
    autoFetchTemplateInfo() { if (!this.createForm.templateNo) return; this.fetchTemplateDesc(); },
    fetchTemplateDesc() {
      fetchTemplateInfo({ templateNo: this.createForm.templateNo, site: this.$store.state.user.site }).then(({data})=> {
        if (data && (data.code===0||data.code==='0')) { const obj=data.obj||{}; this.createForm.templateDesc = obj.templateDesc || obj.templateDescCn || '' } else { this.createForm.templateDesc='' }
      }).catch(()=> { this.createForm.templateDesc='' })
    },
    openTemplateIndicatorDialog() { if (!this.createForm.templateNo) { this.$message.warning('请输入 Template No');
      return } this.templateIndicatorDialogVisible=true; this.loadTemplateIndicators(); },
    loadTemplateIndicators() {
      this.templateIndicatorLoading = true;
      getTemplateIndicators({ templateId: this.createForm.templateId, site: this.$store.state.user.site }).then(({data})=> {
        if (data && (data.code===0||data.code==='0')) { this.templateIndicatorList = data.rows || data.obj || [] } else { this.templateIndicatorList=[] }
      }).catch(()=> { this.templateIndicatorList=[] }).finally(()=> { this.templateIndicatorLoading=false })
    },
    loadSuppliers() {
      this.supplierLoading = true;
      fetchSupplierList({
        site: this.$store.state.user.site,
        supplierNo: this.supplierQuery.supplierNo,
        supplierName: this.supplierQuery.supplierName
      }).then(({data})=> {
        if (data && (data.code===0||data.code==='0')) {
          this.supplierList = (data.page ? data.page.list : (data.rows || data.obj || [])) || []
        } else {
          this.supplierList = []
        }
      }).catch(()=> { this.supplierList=[] }).finally(()=> { this.supplierLoading=false })
    },
    supplierSelectionChange(val) { this.supplierSelected = val },
    loadDepartments() {
      this.deptLoading = true;
      fetchDepartmentList({ templateId: this.createForm.templateId, requestNo: this.createForm.requestNo ? this.createForm.requestNo : '',
        site: this.$store.state.user.site
      }).then(({data})=> {
        if (data && (data.code === 0 || data.code === '0')) {
          // 统一使用 owner 字段
          this.departmentList = data.rows || data.obj || []
          // 加载所有用户列表，用于匹配 ownerDisplay
          this.loadAllUsersForDisplay()
        } else { this.departmentList = [] }
      }).catch(()=> { this.departmentList=[] }).finally(()=> { this.deptLoading=false })
    },
    // 加载所有用户用于匹配显示名称
    loadAllUsersForDisplay() {
      // 使用和 loadOwners 相同的调用方式，传入一个空对象或第一个部门
      const queryParam = this.departmentList.length > 0 ? this.departmentList[0] : {}
      fetchOwnerUserList(queryParam).then(({data})=> {
        if (data && (data.code===0||data.code==='0')) {
          const userList = (data.page? data.page.list : (data.rows||data.obj||[])) || []
          // 为每个有 owner 的部门匹配 userDisplay
          this.departmentList.forEach(dept => {
            if (dept.owner) {
              const matchedUser = userList.find(u => u.username === dept.owner || u.userName === dept.owner)
              if (matchedUser) {
                this.$set(dept, 'ownerDisplay', matchedUser.userDisplay || matchedUser.user_display || '')
              }
            }
          })
        }
      }).catch(()=> {
        // 静默失败，不影响其他数据显示
      })
    },
    openOwnerSelect(row) { this.currentDeptRow = row; this.ownerDialogVisible = true; this.ownerQuery.keyword=''; this.loadOwners(); },
    loadOwners() {
      this.ownerLoading = true;
      fetchOwnerUserList(this.currentDeptRow).then(({data})=> {
        if (data && (data.code===0||data.code==='0')) { this.ownerUserList = (data.page? data.page.list : (data.rows||data.obj||[])) || [] } else { this.ownerUserList=[] }
      }).catch(()=> { this.ownerUserList=[] }).finally(()=> { this.ownerLoading=false })
    },
    confirmOwner(row) {
      if (!this.currentDeptRow || !row) return;
      const uname = row.username || row.userName || row.user_id || ''
      if (!uname) { this.$message.warning('该行缺少 username无法选择'); return }
      // 保存 username 到 owner 字段（用于提交）
      this.$set(this.currentDeptRow, 'owner', uname)
      // 保存 userDisplay 到 ownerDisplay 字段（仅用于显示）
      this.$set(this.currentDeptRow, 'ownerDisplay', row.userDisplay || row.user_display || '')
      this.ownerDialogVisible = false
    },
    clearOwner(row) { row.owner = '' },
    validateCreate() {
      if (this.createForm.templateNo) this.createForm.templateNo = this.createForm.templateNo.trim()
      if (!this.createForm.templateNo) { this.$message.warning('Template No 不能为空'); return false }
      if (!this.createForm.wantedCompleteDate) { this.$message.warning('Wanted Complete Date 不能为空'); return false }
      if (!this.isEdit && this.supplierSelected.length === 0) { this.$message.warning('请至少选择一个供应商'); return false }
      const hasAnyOwner = this.departmentList.some(d => (d.owner && d.owner.toString().trim() !== ''))
      if (!hasAnyOwner) { this.$message.warning('所有部门 Owner 均为空，请至少为一个部门选择 Owner'); return false }
      // 编辑时模板变更且存在已评分指标（score>0）禁止保存
      if (this.isEdit && this.createForm._originalTemplateNo && this.createForm.templateNo !== this.createForm._originalTemplateNo) {
        const hasScored = (this.indicatorList || []).some(i => Number(i.score) > 0)
        if (hasScored) { this.$message.error('存在已评分指标 ，禁止修改模板'); return false }
      }
      return true
    },
    isCompleted(row) { if (!row) return false; const v = (row.status||'').toString().toUpperCase(); return v==='COMPLETED' || v==='已完成'.toUpperCase(); },
  }
}
</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; }
.supplier-panel-header { min-height: 32px; padding: 2px 6px; }
.sub-panel-title { font-size:14px; white-space:nowrap; flex-shrink:0; }
.supplier-header-filters { display:flex; align-items:center; gap:4px; margin-left:8px; flex:1; justify-content:flex-end; }
.supplier-header-filters /deep/ .el-input__inner { height:24px; line-height:24px; font-size:12px; }
.supplier-header-filters ::v-deep .el-input__inner { height:24px; line-height:24px; font-size:12px; }
.supplier-header-filters /deep/ .el-button--mini { padding:4px 8px; font-size:12px; }
.supplier-header-filters ::v-deep .el-button--mini { padding:4px 8px; font-size:12px; }
.create-top-form { margin-top:-6px; }
</style>
