<template>
  <div>
    <el-form :inline="true" label-position="top" :model="searchData" ref="queryForm"
      @keyup.enter.native="getDataList()">
      <el-row :gutter="10">
        <el-col :span="3">
          <el-form-item label="项目编码" prop="projectCode">
            <el-input v-model="searchData.projectCode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="searchData.projectName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="物料编码" prop="partCode">
            <el-input v-model="searchData.partCode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="物料名称" prop="partName">
            <el-input v-model="searchData.partName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="状态" prop="partStatus">
            <el-select v-model="searchData.partStatus" style="width: 100%">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="dict in dict.type.function_project_part_status" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开始时间">
            <div style="display: flex">
              <el-date-picker style="width: 47%" v-model="searchData.startDate" type="date" value-format='yyyy-MM-dd'
                format='yyyy-MM-dd' clearable></el-date-picker>
              <div style="width: 6%;text-align: center" prop="endDate">-</div>
              <el-date-picker style="width: 47%" v-model="searchData.endDate" type="date" value-format='yyyy-MM-dd'
                format='yyyy-MM-dd' clearable></el-date-picker>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label=" ">
            <el-button type="primary" @click="getDataListAll" :disabled="isBatchEditing">查 询</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery" :disabled="isBatchEditing">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 列表 -->
    <el-table @header-dragend="handleColumnResize" height="30vh" :data="dataList" border ref="mainTable"
      highlight-current-row @row-click="projectClickRow" @current-change="changeCurrentRow" v-loading="dataListLoading"
      style="width: 100%;margin-top: 5px">
      <el-table-column v-for="(item,index) in columnList" :key="index" :sortable="item.columnSortable"
        :prop="item.columnProp" :header-align="item.headerAlign" :align="item.align"
        :fixed="item.fixed === ''?false:item.fixed" :min-width="item.columnWidth" :label="item.columnLabel">
        <template slot-scope="scope">
          <!-- <dict-tag v-if="item.columnProp == 'partStatus'" :options="dict.type.function_project_part_status"
            :value="scope.row.partStatus" /> -->
          <span v-if="item.columnProp == 'partStatus'">
              <span :class="getPartStatusClass(scope.row.partStatus)">
                {{ getPartStatusLabel(scope.row.partStatus) }}
              </span>
            </span>
          <div v-else>
            <span v-if="!item.columnHidden">{{ scope.row[item.columnProp] }}</span>
            <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]"
                style="width: 100px; height: 80px" /></span>
          </div>

        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="180" label="操作">
        <template slot-scope="scope">
          <el-link style="cursor: pointer" @click="copyModel(scope.row)" :disabled="isBatchEditing || copyLoading">复制</el-link>
          <el-link style="cursor: pointer" @click="handleUpdate(scope.row)" :disabled="isBatchEditing">编辑</el-link>
          <!-- <el-link style="cursor: pointer" v-if="scope.row.partStatus == '0'" @click="updateProjectPartStatus(scope.row)">下达</el-link> -->
          <el-link v-if="!scope.row.isModelFlag" style="cursor: pointer" @click="handleModal(scope.row)" :disabled="isBatchEditing">新增模具</el-link>
          <!-- <el-link style="cursor: pointer" @click="handleExport(scope.row)">导出</el-link> -->
          <!-- <el-link style="cursor: pointer" @click="deleteProject(scope.row)">删除</el-link> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件 -->
    <el-pagination style="margin-top: 0px" @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" :disabled="isBatchEditing">
    </el-pagination>

    <el-tabs style="margin-top: 0px; width: 100%; height: 100%;font-size: 14px;" v-model="activeTable"
      class="customer-tab" type="border-card" @tab-click="tabClick" :before-leave="beforeLeaveTab">
      <!-- <el-tab-pane label="项目管理事项" name="projectPartProperty"
        :disabled="isBatchEditing && activeTable !== 'projectPartProperty'">
        <projectPartModelTable :projectPartModel="projectPartModel" :projectPart="model"
          @partFinished="getProjectPartModelList"
          @batch-edit-change="onBatchEditChange('projectPartProperty', $event)"
          :auth-flag="true" :height="'33vh'"></projectPartModelTable>
      </el-tab-pane> -->
      <el-tab-pane label="模具开发进度" name="projectPartModel"
        :disabled="isBatchEditing && activeTable !== 'projectPartModel'">
        <ProjectPartModelTableDetail ref="projectPartModelTableDetail" :projectPartModel="projectPartModel"
          @partFinished="getProjectPartModelList" @change="onModelFlagChange"
          @batch-edit-change="onBatchEditChange('projectPartModel', $event)"
          :auth-flag="true" :height="'33vh'"></ProjectPartModelTableDetail>
        <!-- <oss-components ref="inquiryDocument" label="申请单号" style="margin-top: 5px" height="44vh" :columns="ossColumns"
            :disabled="false" :orderRef1="model.site" :orderRef2="model.objectId" :rfqNo="model.projectCode"
            :orderRef5="model.projectId">
          </oss-components> -->
      </el-tab-pane>
      <el-tab-pane label="相关文档" name="inquiryDocument"
        :disabled="isBatchEditing && activeTable !== 'inquiryDocument'">
        <div style="height: 100%;overflow: auto;">
          <oss-components ref="inquiryDocument" label="申请单号" style="margin-top: 5px" height="44vh" :columns="ossColumns"
            :disabled="false" :orderRef1="model.site" :orderRef2="model.projectPartId" :fileTypeCode="1" :rfqNo="model.projectCode"
            :orderRef5="model.projectId" step-name="项目物料">
          </oss-components>
        </div>
      </el-tab-pane>
    </el-tabs>

    <ProjectPartForm ref="projectPartForm" v-if="projectModelVisible" @selectedFinish="getDataList"></ProjectPartForm>
    <ProjectModelFormHeader ref="projectModelFormHeader" v-if="projectModelHeaderVisible" @selectedFinish="getModelFormHeaderList"></ProjectModelFormHeader>
  </div>
</template>
  
  <script>
import {
  queryProjectPartByPage,
  queryProjectPartModelList,
  updateProjectPartStatus,
  handleExport,
  copyProjectManagePart,
} from '@/api/project/project.js'
import ProjectPartModelTable from './modules/projectPartModelTable.vue'
import OssComponents from './modules/ossProjectComponents.vue'
import ProjectPartForm from './modules/projectPartForm.vue'
import ProjectModelFormHeader from './modules/projectModelFormHeader.vue'
import ProjectPartModelTableDetail from './modules/projectPartModelTableDetail.vue'
import { getRoleByUserId } from '@/api/role.js'

export default {
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 跳转后清除 redirectPath
      localStorage.removeItem('redirectPath')
      console.log('redirectPath 已清除')
    })
  },
  dicts: ['function_project_part_status'],
  name: 'projectPartIndex',
  computed: {
    isBatchEditing() {
      return !!(
        (this.batchEditLocks && this.batchEditLocks.projectPartProperty) ||
        (this.batchEditLocks && this.batchEditLocks.projectPartModel)
      )
    },
  },
  components: {
    ProjectPartModelTable,
    OssComponents,
    ProjectPartForm,
    ProjectModelFormHeader,
    ProjectPartModelTableDetail,
  },
  props: {},
  data() {
    return {
      projectPartModel: [],
      model: {},
      loading: false,
      attributeDialog: true,
      projectModelVisible: false,
      projectModelHeaderVisible: false,
      priceCheckRule: {
        associatedPartNo: [{ required: true, message: ' ', trigger: 'change' }],
        materialRequired: [{ required: true, message: ' ', trigger: 'change' }],
        yearlyOrMonthlyRequirement: [
          { required: true, message: ' ', trigger: 'change' },
        ],
        runningWidth: [{ required: true, message: ' ', trigger: 'change' }],
      },
      savePriceDetail: {
        site: '',
        quotationNo: '',
        associatedPartNo: '',
        materialRequired: '',
        yearlyOrMonthlyRequirement: '',
        runningWidth: '',
      },
      priceCheckPropertiesList: [],
      // 导出
      exportData: [],
      resultList: [],
      // ======== 行高 ========
      secondHeight: 200,
      // ======== 分页 ========
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      selectedDataNum: 0,
      ossColumns: [
        {
          userId: this.$store.state.user.name,
          functionId: 101506001001,
          serialNumber: '101506001001Table2FileName',
          tableId: '101506001001Table2',
          tableName: '文件信息表',
          columnProp: 'fileName',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '文件名称',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 140,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 101506001001,
          serialNumber: '101506001001Table2FileRemark',
          tableId: '101506001001Table2',
          tableName: '文件信息表',
          columnProp: 'cadditionalInfo',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '备注',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 240,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 101506001001,
          serialNumber: '101506001001Table2CreateDate',
          tableId: '101506001001Table2',
          tableName: '文件信息表',
          columnProp: 'fileSuffix',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '文件步骤',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 101506001001,
          serialNumber: '101506001001Table2CreateDate',
          tableId: '101506001001Table2',
          tableName: '文件信息表',
          columnProp: 'createDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '上传时间',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 140,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 101506001001,
          serialNumber: '101506001001Table2CreatedBy',
          tableId: '101506001001Table2',
          tableName: '文件信息表',
          columnProp: 'createdBy',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '上传人',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 140,
        },
      ],
      // 条件查询
      searchData: {
        userId: this.$store.state.user.id,
        site: this.$store.state.user.site,
        id: '',
        customerNo: '',
        customerDesc: '',
        projectNo: '',
        projectName: '',
        buNo: '',
        requestStartDate: '',
        requestEndDate: '',
        requiredCompletionStartDate: '',
        requiredCompletionEndDate: '',
        status: '',
        sstatus: '',
        quoterName: '',
        requesterName: '',
        priorityLevel: '',
        orderRef1: 'PJ',
        page: 1,
        limit: 10,
        menuId: this.$route.meta.menuId,
        projectPartId:0,
        partCode:'',
      },
      searchData1: {
        userId: this.$store.state.user.id,
        site: this.$store.state.user.site,
        id: '',
        customerNo: '',
        customerDesc: '',
        projectNo: '',
        bu: '',
        requestStartDate: '',
        requestEndDate: '',
        requiredCompletionStartDate: '',
        requiredCompletionEndDate: '',
        status: '',
        quoterName: '',
        requesterName: '',
        priorityLevel: '',
        orderRef1: 'PJ',
        page: 1,
        limit: 10,
        menuId: this.$route.meta.menuId,
      },
      // 其它
      dataListLoading: false,
      // 选择项目弹框开关
      chooseProjectListFlag: false,
      reviewFlag: false,
      // 初始页签
      activeTable: 'projectPartModel',
      lastActiveTable: 'projectPartProperty',
      tabRollbacking: false,
      copyLoading: false,
      batchEditLocks: {
        projectPartProperty: false,
        projectPartModel: false,
      },
      batchEditLockedTab: '',
      // ======== 数据对象 ========
      modalData: {
        flag: '',
        title: '',
        site: this.$store.state.user.site,
        userName: this.$store.state.user.name,
        id: '',
        projectNo: '',
        customerNo: '',
        customerDesc: '',
        requestDate: '',
        requester: '',
        requesterName: '',
        customerInquiryNo: '',
        priorityLevel: '',
        requiredCompletionDate: '',
        quoter: '',
        quoterName: '',
        status: '',
        remark: '',
        createDate: '',
        createBy: '',
        updateDate: '',
        updateBy: '',
        authHistId: '',
        approveResult: '',
        authHistRemark: '',
        canAuthFlag: '',
        actAuthorizator: '',
        strActAuthorizeDate: this.dayjs().format('YYYY-MM-DD HH:mm:ss'),
        actAuthorizeDate: '',
      },
      inquiryPartItemModalData: {
        bu: '',
        buDesc: '',
        projectNo: '',
        partNo: '',
        partDesc: '',
        umId: '',
        umName: '',
        codeNo: '',
        codeDesc: '',
        textValue: '',
        numValue: '',
        valueType: '',
        valueTypeDb: '',
        valueChooseFlag: '',
        availableValueList: [],
      },
      // ======== 数据列表 ========
      dataList: [],
      inquiryAuthDataList: [],
      // ======== 列表表头 ========
      columnList: [
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '190006Table1QuoteVersionNo',
          tableId: '777002Table1',
          tableName: '项目信息表',
          columnProp: 'projectCode',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '项目编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '190006Table1QuoteDate',
          tableId: '777002Table1',
          tableName: '项目信息表',
          columnProp: 'projectName',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '项目名称',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 160,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1CustomerNo',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'partCode',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '物料编号',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1CustomerDesc',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'partName',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '物料名称',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 140,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1RequesterName',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'partLeader',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '物料负责人',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1QuoterName',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'partCustomerCode',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '客户编号',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1QuoterName',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'partCustomerName',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '客户名称',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 140,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1QuoterName',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'partStatus',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '料号状态',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1QuoterName',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'partEndDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '结案日期',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1QuoterName',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'createBy',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '创建人',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1QuoterName',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'createTime',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '创建时间',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 130,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1QuoterName',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'updateBy',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '更新人',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 777002,
          serialNumber: '5012Table1QuoterName',
          tableId: '777002Table1',
          tableName: '项目信息',
          columnProp: 'updateTime',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '更新时间',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 130,
        },
      ],
      // ======== 必填规则 ========
      inquiryPartRules: {
        bu: [
          { required: true, message: ' ', trigger: 'change' },
          { required: true, message: ' ', trigger: 'blur' },
        ],
        partNo: [
          { required: true, message: ' ', trigger: 'change' },
          { required: true, message: ' ', trigger: 'blur' },
        ],
        partDesc: [
          { required: true, message: ' ', trigger: 'change' },
          { required: true, message: ' ', trigger: 'blur' },
        ],
        inquiryQty: [
          { required: true, message: ' ', trigger: 'change' },
          { required: true, message: ' ', trigger: 'blur' },
        ],
        umId: [
          { required: true, message: ' ', trigger: 'change' },
          { required: true, message: ' ', trigger: 'blur' },
        ],
        codeNo: [
          { required: true, message: ' ', trigger: 'change' },
          { required: true, message: ' ', trigger: 'blur' },
        ],
      },
      // ======== 选中的当前行数据 ========
      projectCurrentRow: {},
      // ======== 模态框开关控制 ========
      modalFlag: false,
      modalDisableFlag: false,
      inquiryPartModalFlag: false,
      inquiryPartModalDisableFlag: false,
      inquiryPartItemModalFlag: false,
    }
  },
  mounted() {
    this.$nextTick(() => {
      /*第二个表格高度的动态调整*/
      this.height = window.innerHeight - 210
    })
  },
  created() {
    // 获取 URL 查询参数
    const project = {
      projectPartId:this.$route.query.projectPartId,
      partCode:this.$route.query.partCode,
    }
    
    // 将查询参数赋值给 searchData
    if (project) {
      this.$set(this.searchData,'projectPartId',project.projectPartId)
      this.$set(this.searchData,'partCode',project.partCode)
    
    }
    // 动态列
    this.getTableUserColumn(this.$route.meta.menuId + 'table1', 1)
    
    this.getDataList()
  },
  activated() {
    this.getDataList()
  },
  watch: {
    activeTable(newVal, oldVal) {
      if (this.tabRollbacking) return
      // 记录上一次可用tab（非批量编辑时）
      if (!this.isBatchEditing) {
        this.lastActiveTable = newVal
        return
      }

      // 批量编辑中：强制回滚到锁定tab（或上一次tab）
      const target = this.batchEditLockedTab || oldVal || this.lastActiveTable
      if (target && newVal !== target) {
        this.tabRollbacking = true
        this.$message.warning('批量编辑中，请先保存或取消后再切换页签')
        this.$nextTick(() => {
          this.activeTable = target
          this.tabRollbacking = false
        })
      }
    },
  },
  methods: {
    onBatchEditChange(source, val) {
      if (!this.batchEditLocks) return
      this.$set(this.batchEditLocks, source, !!val)
      if (!!val) {
        // 进入批量编辑时锁定当前tab
        this.batchEditLockedTab = this.activeTable
      } else if (!this.isBatchEditing) {
        // 全部退出批量编辑后解锁
        this.batchEditLockedTab = ''
      }
    },
    beforeLeaveTab(activeName, oldActiveName) {
      if (this.isBatchEditing) {
        this.$message.warning('批量编辑中，请先保存或取消后再切换页签')
        return false
      }
      return true
    },
    handleColumnResize(newWidth, oldWidth, column, event) {
      let inData = this.columnList.filter(
        (item) => item.columnProp === column.property
      )[0]
      inData.columnWidth = newWidth
      updateColumnSize(inData).then(({ data }) => {
        if (data.code === 0) {
          console.log('栏位宽度保存成功！')
        }
      })
    },
    // ======== 分页相关方法 ========
    /**
     * 每页数
     * @param val
     */
    sizeChangeHandle(val) {
      if (this.isBatchEditing) {
        this.$message.warning('批量编辑中，请先保存或取消')
        return
      }
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    /**
     * 当前页
     * @param val
     */
    currentChangeHandle(val) {
      if (this.isBatchEditing) {
        this.$message.warning('批量编辑中，请先保存或取消')
        return
      }
      this.pageIndex = val
      this.getDataList()
    },

    // ======== 页签切换相关方法 ========
    /**
     * 列表表格选择替换
     * @param tab
     * @param event
     */
    tabClick(tab, event) {
      if (this.isBatchEditing) {
        // 兜底：有些版本不会触发 before-leave 或 disabled 表现不一致
        this.$message.warning('批量编辑中，请先保存或取消后再切换页签')
        const target = this.batchEditLockedTab || this.lastActiveTable
        if (target) this.activeTable = target
        return
      }
      // 刷新列表数据
      this.refreshCurrentTabTable()
    },

    // ======== 列表操作方法 ========
    /**
     * 单机选中询价信息
     * @param row
     */
    projectClickRow(row) {
      if (this.isBatchEditing) {
        this.$message.warning('批量编辑中，请先保存或取消')
        return
      }

      this.projectCurrentRow = JSON.parse(JSON.stringify(row))
      this.model = JSON.parse(JSON.stringify(row))   
      //刷新当前页表
      this.refreshCurrentTabTable()
    },
    /**
     * 当前值发生变化的时候修改
     * @param row
     * @param oldRow
     */
    changeCurrentRow(row, oldRow) {
      if (this.isBatchEditing) return
      // 判断是否是获取焦点的事件
      if (row) {
        this.projectCurrentRow = JSON.parse(JSON.stringify(row))
      }
    },
    /**
     * 刷新页签的table数据
     */
    refreshCurrentTabTable() {
      this.getTabs()
    },

    // ======== 列表数据刷新方法 ========
    /**
     * 获取数据列表
     */
    getDataListAll() {
      if (this.isBatchEditing) {
        this.$message.warning('批量编辑中，请先保存或取消')
        return
      }
      this.searchData1 = null
      this.getDataList()
    },

    getDataList() {
      if (this.isBatchEditing) {
        this.$message.warning('批量编辑中，请先保存或取消')
        return
      }
      //console.log(this.searchData1)
      this.searchData.pageSize = this.pageSize
      this.searchData.pageNo = this.pageIndex
      
      let inData = this.searchData
      queryProjectPartByPage(inData).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records
          this.pageIndex = data.page.current
          this.pageSize = data.page.size
          this.totalPage = data.page.total
          this.dataList.forEach((item) => {
            if (item.groupDesc === '' || item.groupDesc === null) {
              item.auth = item.userDisplay
            } else {
              item.auth = item.groupDesc
            }
          })
          //判断是否全部存在数据
          if (this.totalPage > 0) {
            //设置选中行
            this.$refs.mainTable.setCurrentRow(this.dataList[0])
            this.projectClickRow(this.dataList[0])
          }
        }
        this.dataListLoading = false
      })
    },
    getTabs() {
      switch (this.activeTable) {
        case 'projectPartProperty':
          this.getProjectPartModelList()
          break
        case 'projectPartModel':
          this.$refs.projectPartModelTableDetail.handleQuery(this.model)
          break
        case 'inquiryDocument':
          this.$refs.inquiryDocument.handleQuery()
          break
        default:
          this.getProjectPartModelList()
          break
      }
    },
    getProjectPartModelList() {
      let obj = {
        projectPartId: this.model.projectPartId,
      }
      queryProjectPartModelList(obj).then(({ data }) => {
        if (data && data.code === 0) {
          this.projectPartModel = data.list
          this.getRoleByUserId()
        } else {
          this.$message.warning(data.msg)
        }
      })
    },
    partFinished() {
      this.getProjectPartModelList()
    },
    deleteProject(row) {
      this.$confirm('确认删除该项目信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.handleRemoveProject(row)
        })
        .catch(() => {})
    },
    handleRemoveProject(row) {
      let params = {
        projectId: row.projectId,
      }
      projectDeleteById(params).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success(data.msg)
          this.getDataList()
        }
      })
    },
    // /**
    //  * 获得这些询价号的全部附件
    //  */
    // getFileContentList () {
    //   let currentData = {
    //     orderRef1: this.$store.state.user.site,
    //     orderRef2: this.enterResultData.quotationNo
    //   }
    //   getFileContentList(currentData).then(({data}) => {
    //     if (data && data.code === 0) {
    //       this.enterResultData.fileContentList = data.rows
    //     } else {
    //       this.enterResultData.fileContentList = []
    //     }
    //   })
    // },

    updateModal(row) {
      this.modalData = JSON.parse(JSON.stringify(row))
      this.modalData.strActAuthorizeDate = this.dayjs().format(
        'YYYY-MM-DD HH:mm:ss'
      )
      this.modalData.userName = this.$store.state.user.name
      this.reviewFlag = true
    },

    saveReview(row, val) {
      if (row.authHistRemark == '') {
        this.$alert(data.msg, '操作提示', {
          confirmButtonText: '确定',
          callback: (action) => {
            this.saveButton = false
          },
        })
      }
      this.loading = true
      this.modalData.id = row.authHistId
      this.modalData.actAuthorizator = row.userName
      this.modalData.remark = row.authHistRemark
      this.modalData.actAuthorizeDate = row.strActAuthorizeDate
      this.modalData.orderRef1 = row.projectNo
      if (val === 'Y') {
        if (row.lastStepFlag === 'Y') {
          this.modalData.approveResult = '已审批'
        } else {
          this.modalData.approveResult = '已审批'
        }
      } else if (val === 'N') {
        this.modalData.approveResult = '未通过'
      }
      updateProjectAuthHist(this.modalData).then(({ data }) => {
        if (data && data.code === 0) {
          this.getDataList()
          this.reviewFlag = false
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {},
          })
        } else {
          this.$alert(data.msg, '错误', {
            confirmButtonText: '确定',
          })
        }
        this.loading = false
      })
    },

    getRoleByUserId() {
      for (let i = 0; i < this.projectPartModel.length; i++) {
        this.$set(this.projectPartModel[i], 'planEndDateDisabled', false)
      }
      if (this.$store.state.user.id === 1) {
        return
      }
      let params = {
        userId: this.$store.state.user.id,
      }
      getRoleByUserId(params)
        .then((res) => {
          if (res && res.data.code === 0) {
            let hasManager = res.data.roles.includes('manager')
            for (let i = 0; i < this.projectPartModel.length; i++) {
              if (!hasManager && this.projectPartModel[i].planEndDate) {
                this.projectPartModel[i].planEndDateDisabled = true
              } else {
                this.projectPartModel[i].planEndDateDisabled = false
              }
            }
            console.log('获取角色信息成功:', this.projectPartModel);
            
          } else {
            this.$message.warning(res.data.msg)
          }
        })
        .catch((error) => {
          this.$message.error(error)
        })
    },
    // ======== 导出相关方法 ========
    /**
     * 导出excel
     */
    async createExportData() {
      this.searchData.limit = -1
      this.searchData.page = 1
      await queryProjectPartByPage(this.searchData).then(({ data }) => {
        this.resultList = data.page.list
      })
      return this.resultList
    },
    startDownload() {},
    finishDownload() {},
    fields() {
      let json = '{'
      this.columnList.forEach((item, index) => {
        if (index == this.columnList.length - 1) {
          json +=
            '"' + item.columnLabel + '"' + ':' + '"' + item.columnProp + '"'
        } else {
          json +=
            '"' +
            item.columnLabel +
            '"' +
            ':' +
            '"' +
            item.columnProp +
            '"' +
            ','
        }
      })
      json += '}'
      let s = eval('(' + json + ')')
      return s
    },
    // ========  导入相关方法 ========
    handleImportQuotation() {
      let currentData = {
        createBy: this.$store.state.user.name,
        site: this.$store.state.user.site,
      }
      //打开组件 去做新增业务
      this.$nextTick(() => {
        this.$refs.quotationUpload.init(currentData)
      })
    },
    handleUpdate(row) {
      this.projectModelVisible = true
      this.$nextTick(() => {
        this.$refs.projectPartForm.edit(row)
      })
    },
    handleModal(row) {
      this.projectModelHeaderVisible = true
      this.$nextTick(() => {
        this.$refs.projectModelFormHeader.edit(row)
      })
    },
    copyModel(row) {
      if (this.copyLoading) return
      this.copyLoading = true
      let params = {
        projectPartId: row.projectPartId,
        site: this.$store.state.user.site,
      }
      copyProjectManagePart(params).then(({ data }) => {
        if (data && data.code === 0) {
          this.getDataList()
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {},
          })
        } else {
          this.$alert(data.msg, '错误', {
            confirmButtonText: '确定',
          })
        }
      }).finally(() => {
        this.copyLoading = false
      })
    },
    // 保存弹框关闭事件
    closeSaveDataDialog() {
      this.modalData = {
        flag: '',
        title: '',
        site: '',
        bu: '',
        buNo: '',
        buDesc: '',
        id: '',
        projectNo: '',
        customerNo: '',
        customerDesc: '',
        requester: '',
        requesterName: '',
        quoter: '',
        quoterName: '',
        customerInquiryNo: '',
        status: '',
        priorityLevel: '',
        requestDate: '',
        requiredCompletionDate: '',
        remark: '',
      }
      this.modalFlag = false
    },
    rowStyle({ row }) {
      if (this.projectCurrentRow.id === row.id) {
        return { 'background-color': '#E8F7F6', cursor: 'pointer' }
      }
    },
    // 动态列开始 获取 用户保存的 格式列
    async getTableUserColumn(tableId, columnId) {
      let queryTableUser = {
        userId: this.$store.state.user.name,
        functionId: this.$route.meta.menuId,
        tableId: tableId,
        status: true,
        languageCode: this.$i18n.locale,
      }
      /* await getTableUserListLanguage(queryTableUser).then(({ data }) => {
        if (data.rows.length > 0) {
          switch (columnId) {
            case 1:
              this.columnList = data.rows
              break
          }
        } else {
          this.getColumnList(tableId, columnId)
        }
      }) */
    },

    // 获取 tableDefault 列
    async getColumnList(tableId, columnId) {
      let queryTable = {
        functionId: this.$route.meta.menuId,
        tableId: tableId,
        languageCode: this.$i18n.locale,
      }
      await getTableDefaultListLanguage(queryTable).then(({ data }) => {
        if (!data.rows.length === 0) {
          switch (columnId) {
            case 1:
              this.columnList = data.rows
              break
          }
        }
      })
    },
    resetQuery() {
      if (this.isBatchEditing) {
        this.$message.warning('批量编辑中，请先保存或取消')
        return
      }
      this.$set(this.searchData, 'startDate', '')
      this.$set(this.searchData, 'endDate', '')
      this.resetForm('queryForm')
      this.getDataList()
    },
    updateProjectPartStatus(row){
      updateProjectPartStatus(row).then(({data})=>{
        
        if (data && data.code === 0) {
          this.getDataList()
        }
      })
    },
    onModelFlagChange(){

    },
    // 获取项目物料状态标签
    getPartStatusLabel(status) {
      const statusDict = this.dict.type.function_project_part_status
      const statusItem = statusDict.find(item => item.value === status)
      return statusItem ? statusItem.label : status
    },
    // 获取项目物料状态样式类
    getPartStatusClass(status) {
      switch (status) {
        case '3':
          return 'status-green'
        case '4':
          return 'status-yellow'
        case '5':
          return 'status-red'
        default:
          return ''
      }
    },
    getModelFormHeaderList(){
      this.searchData.pageSize = this.pageSize
      this.searchData.pageNo = this.pageIndex
      let inData = this.searchData
      queryProjectPartByPage(inData).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records
          this.pageIndex = data.page.current
          this.pageSize = data.page.size
          this.totalPage = data.page.total

          //判断是否全部存在数据
          if (this.totalPage > 0) {
            //设置选中行
            this.$nextTick(() => {
              const current = this.dataList.find(item => item.projectPartId === this.model.projectPartId)
              if (current) {
                this.$refs.mainTable.setCurrentRow(current)
                this.projectClickRow(current)
              }
            })
          }
        }
        this.dataListLoading = false
      })
    },
    handleExport(row){
    console.log(row); 
    
    handleExport(row).then(response => {
        // 接受blob二进制流
        const blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
        // 根据blob创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob);
        // 创建a标签
        const link = document.createElement('a');
        link.href = downloadUrl;
        
        // 文件名处理
        let fileName = '默认文件名.xlsx';
        const contentDisposition = response.headers['content-disposition'];
        if (contentDisposition) {
            const fileNameMatch = contentDisposition.match(/filename=(.+)/);
            fileName = fileNameMatch ? decodeURIComponent(fileNameMatch[1]) : fileName;
        }
        link.download = fileName;
        
        document.body.appendChild(link);
        link.click();
        // 🧹内存清理
        window.URL.revokeObjectURL(downloadUrl);
        document.body.removeChild(link);
    }).catch(error => {
        this.$message.error('导出失败: ' + error.message);
    });

  },
  },
  
}
</script>
  
<style scoped>
/deep/ .customer-tab .el-tabs__content {
  padding: 0px !important;
  height: 100%;
}

/deep/ .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
  background-color: #17b3a3;
  border-color: #17b3a3;
}

/deep/ .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
  border-color: #fff;
}
/deep/ .el-form-item--medium .el-form-item__content {
  height: auto;
}

.el-input-number /deep/ .el-input__inner {
  text-align: right;
  padding-right: 5px !important;
}

/deep/ .el-input .el-input--medium {
  line-height: 20px;
}
/deep/ .el-input-number .el-input--medium {
  line-height: 20px;
}

/*table中input 修改样式*/
/deep/ div.table-el-date {
  padding: 0px 0px;
  height: 25px !important;
}

/*table中input*/
div.table-el-date /deep/ input.el-input__inner {
  padding: 0px 0px;
  height: 23px !important;
  text-align: right;
}

/* 特殊的样式*/
/deep/ .el-table div.cell:has(.table-el-date) {
  /* 直接作用于 <td> 元素 */
  padding: 0px;
  height: 25px;
}

.el-transfer-panel {
  border: 2px solid #17b3a3;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  display: inline-block;
  vertical-align: middle;
  width: 200px;
  max-height: 100%;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  position: relative;
}

.el-transfer-panel .el-transfer-panel__header {
  height: 40px;
  line-height: 40px;
  background: #17b3a3;
  margin: 0;
  padding-left: 15px;
  border-bottom: 1px solid #17b3a3;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #000;
}

.el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label {
  font-size: 14px;
  color: #303133;
  font-weight: 400;
}

/* 项目物料状态颜色样式 */
.status-green {
  color: #67c23a;
}

.status-yellow {
  color: #e6a23c;
}

.status-red {
  color: #f56c6c;
}
</style>