<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <div class="switch" v-if="!contactData?.id">
        <div class="switch_left">
          <ul>
            <li
              style="height: 42px; line-height: 38px"
              v-for="item in tabOptions"
              :key="item.key"
              :class="{ active: activeComp == item.key }"
              @click="activeComp = item.key"
            >
              <el-badge
                :value="toDoReminder[item.reminder] || 0"
                class="item"
                v-if="item.reminder"
              >
                {{ item.name }}
              </el-badge>
              <span v-else>{{ item.name }}</span>
            </li>
          </ul>
        </div>
      </div>
      <div class="main" style="padding: 0 10px">
        <div v-if="activeComp == 'saleorder'">
          <div class="ele-border-lighter form-content" v-loading="loading">
            <search-table @search="reload"></search-table>
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
              <el-tab-pane label="全部" name="all"></el-tab-pane>
              <el-tab-pane label="待发货" name="700"></el-tab-pane>
              <el-tab-pane label="部分发货" name="701"></el-tab-pane>
              <el-tab-pane label="全部发货" name="800"></el-tab-pane>
            </el-tabs>
            <!-- 数据表格 -->
             <div v-table-scroll-sync class="table-container">
              <ele-pro-table
                ref="table"
                :columns="columns"
                :datasource="datasource"
                height="calc(100vh - 400px)"
                style="margin-bottom: 10px"
                full-height="calc(100vh - 116px)"
                tool-class="ele-toolbar-form"
                :selection.sync="selection"
                :page-size="20"
                @columns-change="handleColumnChange"
                :cache-key="cacheKeyUrl"
                show-summary
                :summary-method="getSummaries"
              >
                <!-- 表头工具栏 -->
                <template v-slot:toolbar>
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-plus"
                    class="ele-btn-icon"
                    @click="openEditNew('add', {})"
                    v-if="$hasPermission('eom:saleorder:save')"
                  >
                    新建
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    icon="el-icon-delete"
                    class="ele-btn-icon"
                    @click="allDelBtn"
                    v-if="$hasPermission('eom:saleorder:delete')"
                    :disabled="selection?.length === 0"
                  >
                    批量删除
                  </el-button>
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-plus"
                    class="ele-btn-icon"
                    @click="invoiceAll"
                    v-if="$hasPermission('eom:saleManage:invoiceAll')"
                    :disabled="selection?.length === 0"
                  >
                    批量发货
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-upload2"
                    @click="uploadFile"
                    v-if="$hasPermission('eom:saleorder:save')"
                    >导入</el-button
                  >
                  <exportButton
                    btnName="列表导出"
                    fileName="销售订单"
                    apiUrl="/eom/saleorder/export"
                    :params="exportParams"
                  ></exportButton>

                  <el-button
                    v-if="$hasPermission('eom:saleorder:push')"
                    size="small"
                    type="primary"
                    class="ele-btn-icon"
                    @click="allPushBtn"
                    :disabled="selection?.length === 0"
                  >
                    批量推送
                  </el-button>

                  <el-dropdown
                    trigger="click"
                    :disabled="selection?.length === 0"
                  >
                    <el-button
                      type="primary"
                      class="el-icon-printer"
                      size="small"
                    >
                      打印<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        v-if="$hasPermission('eom:saleorder:print')"
                        @click.native="handlePrint"
                        >打印</el-dropdown-item
                      >
                      <el-dropdown-item
                        v-if="$hasPermission('eom:saleorder:printRt')"
                        @click.native="handleRtPrint"
                        >打印（润天）</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>

                <!-- 查看详情列 -->
                <template v-slot:relationCode="{ row }">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="openRelationCodeDetail(row)"
                  >
                    {{ row.relationCode }}
                  </el-link>
                </template>
                <template v-slot:orderNo="{ row }">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="openorderDetail(row)"
                  >
                    {{ row.orderNo }}
                  </el-link>
                </template>
                <!-- 预销售订单编码 -->
                <template v-slot:preOrderNo="{ row }">
                  <el-input
                    v-model="row.preOrderNo"
                    @keyup.enter.native="handlePreOrderNoBlur(row)"
                    style="width: 100%; padding: 0 4px"
                    placeholder="请输入预销售编码"
                  ></el-input>
                </template>
                <!-- 操作列 -->
                <template v-slot:action="{ row }">
                  <el-link
                    type="primary"
                    :underline="false"
                    icon="el-icon-edit"
                    @click="openEditNew('edit', row)"
                    v-if="
                      $hasPermission('eom:saleorder:update') &&
                      [0, 3].includes(row.orderStatus)
                    "
                  >
                    修改
                  </el-link>
                  <el-link
                    type="primary"
                    :underline="false"
                    icon="el-icon-plus"
                    @click="saleOrderSubmitOrGenerate(row)"
                    v-if="
                      [0, 3].includes(row.orderStatus) &&
                      $hasPermission('eom:saleorder:update')
                    "
                  >
                    提交
                  </el-link>
                  <!-- <el-link
                    type="primary"
                    :underline="false"
                    icon="el-icon-plus"
                    @click="handleAutoGenerate(row.id)"
                    v-if="
                      [2].includes(row.orderStatus) &&
                      row.needProduce &&
                      !!!row.purchasePlanNum
                    "
                  >
                    生成采购计划
                  </el-link> -->

                  <el-popconfirm
                    class="ele-action"
                    title="确定要删除此信息吗？"
                    @confirm="remove([row.id])"
                    v-if="
                      [0, 3].includes(row.orderStatus) &&
                      $hasPermission('eom:saleorder:delete')
                    "
                  >
                    <template v-slot:reference>
                      <el-link
                        type="danger"
                        :underline="false"
                        icon="el-icon-delete"
                      >
                        删除
                      </el-link>
                    </template>
                  </el-popconfirm>

                  <el-link
                    type="primary"
                    :underline="false"
                    icon="el-icon-plus"
                    @click="handleCommand('adjustment', row)"
                    v-if="row.allowDifference == 1 && $hasPermission('eom:saleorder:adjustment')"
                  >
                    冲差
                  </el-link>
                  <el-link
                    type="primary"
                    :underline="false"
                    icon="el-icon-plus"
                    @click="handleCommand('invoice', row)"
                    v-if="
                      [2].includes(row.orderStatus) &&
                      ((row.saleTypeName.includes('受托') &&
                        row.isEntrustedReceive == 1) ||
                        !row.saleTypeName.includes('受托')) &&
                      $hasPermission('eom:saleordersendrecord:save') &&
                      ((isTotalCount == '1' &&
                        row.sendTotalCount < row.productCount) ||
                        isTotalCount == 0)
                    "
                  >
                    发货单
                  </el-link>
                  <el-link
                    type="primary"
                    :underline="false"
                    icon="el-icon-plus"
                    @click="handleCommand('entrustedReceive', row)"
                    v-if="
                      [2].includes(row.orderStatus) &&
                      row.saleTypeName.includes('受托') &&
                      row.isEntrustedReceive != 1
                    "
                  >
                    受托收货单
                  </el-link>
                  <el-link
                    type="primary"
                    :underline="false"
                    icon="el-icon-plus"
                    @click="handleCommand('saleOrderReminder', row)"
                    v-if="
                      [2].includes(row.orderStatus) &&
                      clientEnvironmentId != 5 &&
                      row.progress < 800
                    "
                  >
                    催单
                  </el-link>
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="finish('single', row)"
                    v-if="
                      [2].includes(row.orderStatus) &&
                      row.progress != 1000
                    "
                  >
                    完结
                  </el-link>
                  <!-- <el-link
                    type="primary"
                    :underline="false"
                    icon="el-icon-plus"
                    @click="handleCommand('invoiceManage', row)"
                    v-if="
                      [2].includes(row.orderStatus) &&
                      !row.hasInvoiceApply &&
                      $hasPermission('eom:fininvoiceapply:save')
                    "
                  >
                    新增发票
                  </el-link> -->
                </template>
              </ele-pro-table>
            </div>
          </div>
        </div>
        <div v-if="activeComp == 'invoice'">
          <invoice @getToDoReminder="getToDoReminder"></invoice>
        </div>
        <div v-if="activeComp == 'invoiceConfirm'">
          <invoice-confirm @getToDoReminder="getToDoReminder"></invoice-confirm>
        </div>
        <div v-if="activeComp == 'entrustedReceive'">
          <entrustedReceive
            @getToDoReminder="getToDoReminder"
          ></entrustedReceive>
        </div>
        <div v-if="activeComp == 'returnorder'" class="returnorder">
          <return-goods @getToDoReminder="getToDoReminder"></return-goods>
        </div>
        <div v-if="activeComp == 'accountstatement'">
          <accountstatement
            @getToDoReminder="getToDoReminder"
          ></accountstatement>
        </div>
        <div v-if="activeComp == 'customerReturnOrder'">
          <customerReturnOrder
            @getToDoReminder="getToDoReminder"
          ></customerReturnOrder>
        </div>
        <div v-if="activeComp == 'exceptionList'">
          <exceptionList @getToDoReminder="getToDoReminder"></exceptionList>
        </div>
        <div v-if="activeComp == 'trayList'">
          <palletManagement
            @getToDoReminder="getToDoReminder"
          ></palletManagement>
        </div>
        <div v-if="activeComp == 'adjustmentNote'">
          <adjustmentNote
            @getToDoReminder="getToDoReminder"
          ></adjustmentNote>
        </div>
        <div v-if="activeComp == 'suspend'">
          <suspend
            @getToDoReminder="getToDoReminder"
          ></suspend>
        </div>
      </div>
    </el-card>

    <add-dialog
      :isRequired="isRequired"
      ref="addDialogRef"
      @done="reload"
      :contactData="contactData"
    ></add-dialog>

    <add-dialog-new
      :isRequired="isRequired"
      ref="addDialogNewRef"
      @done="reload"
      :contactData="contactData"
    ></add-dialog-new>

    <add-invoice-dialog
      ref="invoiceDialogRef"
      @done="reload"
      :contactData="contactData"
    ></add-invoice-dialog>
    <add-return-goods-dialog
      ref="addReturnGoodsRef"
      :contactData="contactData"
      @done="reload"
    ></add-return-goods-dialog>
    <contractr-detail ref="contractDetailRef"></contractr-detail>
    <detail-dialog ref="contactDetailDialogRef"></detail-dialog>
    <autogenerate-dialog
      ref="autogenerateDialogRef"
      @handleSubmit="saleOrderSubmit"
      @reload="reload"
    ></autogenerate-dialog>
    <!-- 多选删除弹窗 -->
    <pop-modal
      :visible.sync="delVisible"
      content="是否确定删除？"
      @done="commitBtn"
    />
    <drawer ref="drawerRef"></drawer>
    <process-submit-dialog
      :isNotNeedProcess="true"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      :isCloseRefresh="false"
      ref="processSubmitDialogRef"
      @reload="reload"
      :callBack="callBack"
    ></process-submit-dialog>
    <addInvoiceManage
      :add-or-edit-dialog-flag.sync="addOrEditDialogFlag1"
      ref="addOrEditDialogRef"
      v-if="addOrEditDialogFlag1"
      @reload="reload"
    ></addInvoiceManage>
    <importDialog
      ref="importDialogRef"
      @success="reload"
      :fileUrl="'/eom/saleorder/importTemplate'"
      :isWeb="false"
      fileName="销售订单导入模板"
      apiUrl="/eom/saleorder/importFile"
    />
    <bomDialog ref="bomDialogRef" :isCloseRefresh="false" @handleSubmit="bomDialogSuccess" @reload="reload"></bomDialog>
    <opportunityDetail ref="opportunityDetailRef"></opportunityDetail>
    <quotationDetail ref="quotationDetailRef"></quotationDetail>
    <addEntrustedReceive
      ref="addEntrustedReceiveRef"
      @done="reload"
      :add-or-edit-dialog-flag.sync="addEntrustedReceiveFlag"
      v-if="addEntrustedReceiveFlag"
    ></addEntrustedReceive>
    <printTemplateSaleOrder
      :groupName="groupName"
      ref="printTemplateSaleOrderRef"
    ></printTemplateSaleOrder>
    <printTemplateHt ref="printTemplateHtRef" :groupName="groupName"></printTemplateHt>
    <printTemplateRt ref="printTemplateRtRef" :groupName="groupName"></printTemplateRt>
    <add-adjust-dialog
      v-if="addAdjustDialogFlag"
      :addAdjustDialogFlag.sync="addAdjustDialogFlag"
      ref="addAdjustDialogRef"
      @done="reload"
    ></add-adjust-dialog>
  </div>
</template>

<script>
import { getSummaries } from '@/utils/util.js';
import searchTable from './components/searchTable.vue';
import addDialog from './components/addDialog.vue';
import addDialogNew from './components/addDialogNew.vue';
import invoice from './invoice/index.vue';
import invoiceConfirm from './invoiceConfirm/index.vue';
import detailDialog from './components/detailDialog.vue';
import exceptionList from './exceptionManagement/exceptionList';
import bomDialog from './components/bomDialog';
import suspend from './suspend/index.vue'; 
import drawer from './components/drawer.vue';
import contractrDetail from '@/views/contractManage/contractBook/components/detailDialog.vue';
import addInvoiceDialog from '@/views/saleManage/saleOrder/invoice/components/addInvoiceDialog';
import addReturnGoodsDialog from '@/views/saleManage/saleOrder/returnGoods/components/addReturnGoodsDialog';
import popModal from '@/components/pop-modal';
import accountstatement from './accountstatement/index.vue';
import customerReturnOrder from './customerReturnOrder/index.vue';
import returnGoods from './returnGoods/index.vue';
import palletManagement from './palletManagement/index.vue';
import addInvoiceManage from '@/views/financialManage/invoiceManage/components/addOrEditDialog.vue';
import addEntrustedReceive from '@/views/saleManage/saleOrder/entrustedReceive/components/addOrEditDialog';
import adjustmentNote from './adjustmentNote‌/index.vue';
import addAdjustDialog from '@/views/saleManage/saleOrder/adjustmentNote‌/components/addAdjustDialog.vue';
import {
  deleteInformation,
  getSaleOrderDetail,
  getTableList,
  saleOrderReminder,
  getByRepeatBomAttribute,
  saveOrderBomList,
  updateOrderInfo,
  saleOrderAdd,
  batchCompleted
} from '@/api/saleManage/saleorder';
import { getToDoReminder } from '@/api/common/index';
import { exportSaleorder } from '@/api/system/file/index.js';
import dictMixins from '@/mixins/dictMixins';
import { reviewStatus, saleOrderProgressStatusEnum, saleOrderStatusEnum } from '@/enum/dict';
import entrustedReceive from '@/views/saleManage/saleOrder/entrustedReceive/index.vue';
import autogenerateDialog from '@/BIZComponents/autogenerateDialog.vue';
import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
import tabMixins from '@/mixins/tableColumnsMixin';
import importDialog from '@/components/upload/import-dialog.vue';
import exportButton from '@/components/upload/exportButton.vue';
import { parameterGetByCode } from '@/api/main/index.js';
import opportunityDetail from '@/views/saleManage/businessOpportunity/components/opportunityDetailDialog.vue';
import quotationDetail from '@/views/saleManage/quotation/components/detailDialog.vue';
import printTemplateSaleOrder from './components/printTemplateSaleOrder.vue';
import { enterprisePage } from '@/api/contractManage/contractBook';
import { listOrganizations } from '@/api/system/organization';
import printTemplateHt from './components/printTemplateHt.vue';
import printTemplateRt from './components/printTemplateRt.vue';


export default {
  mixins: [dictMixins, tabMixins],
  components: {
    processSubmitDialog,
    autogenerateDialog,
    searchTable,
    returnGoods,
    accountstatement,
    popModal,
    contractrDetail,
    addReturnGoodsDialog,
    addInvoiceDialog,
    invoice,
    addDialog,
    detailDialog,
    customerReturnOrder,
    entrustedReceive,
    invoiceConfirm,
    drawer,
    exceptionList,
    addInvoiceManage,
    palletManagement,
    exportButton,
    importDialog,
    bomDialog,
    opportunityDetail,
    quotationDetail,
    addEntrustedReceive,
    printTemplateSaleOrder,
    adjustmentNote,
    addAdjustDialog,
    suspend,
    addDialogNew,
    printTemplateHt,
    printTemplateRt
  },
  //客户管理数据
  props: {
    contactData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      activeName: 'all',
      activeComp: 'saleorder',
      tabOptions: [
        { key: 'saleorder', name: '销售订单', reminder: 'salesOrderNum' },
        {
          key: 'entrustedReceive',
          name: '受托收货单',
          reminder: 'entrustedReceiptNum'
        },
        { key: 'invoice', name: '发货单', reminder: 'deliveryNoteNum' },
        {
          key: 'invoiceConfirm',
          name: '发货确认单',
          reminder: 'deliveryConfirmationFormNum'
        },
        { key: 'trayList', name: '托盘清单' },
        {
          key: 'exceptionList',
          name: '异常列表',
          reminder: 'exceptionListNum'
        },
        { key: 'returnorder', name: '退货单', reminder: 'returnOrderNum' },
        {
          key: 'customerReturnOrder',
          name: '退货处理单',
          reminder: 'returnProcessingFormNum'
        },
        {
          key: 'accountstatement',
          name: '对账单',
          reminder: 'statementAccountNum'
        },
        {
          key: 'adjustmentNote',
          name: '冲差单',
          reminder: 'punchSlipOrderNum'
        },
        {
          key: 'suspend',
          name: '挂单',
          reminder: 'suspendNum'
        },
      ],
      selection: [], //单选中集合
      delVisible: false, //批量删除弹框状态
      loading: false, // 加载状态
      processSubmitDialogFlag: false, // 加载状态
      addOrEditDialogFlag1: false,
      addEntrustedReceiveFlag: false,
      addAdjustDialogFlag: false, //冲差状态
      params: {},
      tableList: [],
      current: null,
      cacheKeyUrl: 'eos-c2e9664a-saleManage-saleOrder',
      isRequired: true,
      isTotalCount: '0',
      columnsVersion: 1,
      timeR: null,
      toDoReminder: {},
      groupName: '',
      organizations: []
    };
  },

  created() {
    enterprisePage({
      pageNum: 1,
      size: 200
    }).then((res) => {
      if (res.list?.length > 0) {
        this.groupName = res.list[0].name;
      }
    });
    this.requestDict('客户状态');
    parameterGetByCode({
      code: 'order_person_info'
    }).then((res) => {
      if (res.value) {
        this.isRequired = res.value === '1';
      }
    });
    //销售发货数量是否限制不能大于采购总数//0否 1是
    parameterGetByCode({
      code: 'saleOrder_invoice_productList_totalCount'
    }).then((res) => {
      this.isTotalCount = res.value;
    });
    this.getToDoReminder();
    this.getInfo();
    this.timeR = setInterval(() => {
      this.getToDoReminder();
    }, 60000);

    // if (!('Notification' in window)) {
    //   console.log('此浏览器不支持桌面通知');
    // } else if (Notification.permission === 'granted') {
    //   // 如果用户已经授权，直接创建通知
    //   var notification = new Notification('标题', {
    //     body: '这是通知的内容。'
    //   });
    // } else if (Notification.permission !== 'denied') {
    //   // 请求权限
    //   Notification.requestPermission().then(function (permission) {
    //     if (permission === 'granted') {
    //       var notification = new Notification('标题', {
    //         body: '消息提醒1'
    //       });
    //     }
    //   });
    // }
  },
  beforeDestroy() {
    clearInterval(this.timeR);
  },
  computed: {
    exportParams() {
      return {
        ...this.params,
        orderIds: this.selection.map(item => item.id)
      }
    },
    clientEnvironmentId() {
      return this.$store.state.user.info.clientEnvironmentId;
    },
    columns() {
      let columnsVersion = this.columnsVersion;
      return [
        {
          width: 45,
          type: 'selection',
          columnKey: 'selection',
          align: 'center'
        },
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'orderNo',
          label: '订单编码',
          align: 'center',
          slot: 'orderNo',
          showOverflowTooltip: true,
          sortable: true,
          minWidth: 200,
          fixed: 'left'
        },
        {
          prop: 'needProduce',
          label: '订单类型',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,

          formatter: (_row, _column, cellValue) => {
            let businessType =
              cellValue == 1
                ? '有客户生产性订单'
                : cellValue == 2
                ? '无客户生产性订单'
                : cellValue == 4
                ? '不定向订单'
                : cellValue == 5
                ? '委外订单'
                : '库存式订单';

            return businessType;
          }
        },

        {
          prop: 'preOrderNo',
          label: '预销售订单编码',
          align: 'center',
          slot: 'preOrderNo', 
          showOverflowTooltip: true,
          sortable: true,
          minWidth: 200,
          fixed: 'left'
        },
        {
          prop: 'createDept',
          columnKey: 'createDept',
          label: '发起人所属部门',
          minWidth: 200,
          align: 'center',
          showOverflowTooltip: true,
          formatter: (_row, _column, cellValue) => {
            if (!cellValue) return ''; 

            const matchedDept = this.organizations.find(
              (dept) => dept.id === cellValue 
            );

            return matchedDept ? matchedDept.name : '';
          }
        },
        {
          prop: 'relationType',
          label: '来源类型',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,
          formatter: (_row, _column, cellValue) => {
            let businessType =
              cellValue == 1
                ? '商机'
                : cellValue == 2
                ? '报价'
                : cellValue == 3
                ? '销售合同'
                : cellValue == 4
                ? '项目'
                : '';

            return businessType;
          }
        },
        {
          prop: 'relationCode',
          label: '来源单据',
          align: 'center',
          slot: 'relationCode',
          showOverflowTooltip: true,
          minWidth: 200,
          formatter: (_row, _column, cellValue) => {
            return _row.relationCode;
          }
        },
        {
          prop: 'progress',
          label: '订单进度',
          align: 'center',
          showOverflowTooltip: true,
          formatter: (_row, _column, cellValue) => {
            return saleOrderProgressStatusEnum.find(
              (val) => val.value == _row.progress
            )?.label;
          },
          minWidth: 120
        },

        // {
        //   prop: 'deliveryDate',
        //   label: '交货日期',
        //   align: 'center',
        //   showOverflowTooltip: true,
        //   minWidth: 200
        // },
        {
          prop: 'productNames',
          label: '产品名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 140
        },
        {
          prop: 'productCodes',
          label: '编码',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 140
        },
        {
          minWidth: 160,
          prop: 'productionCodes',
          label: '生产编号',
          align: 'center'
        },
        {
          prop: 'batchNos',
          label: '批次号',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 140
        },
        {
          prop: 'productCount',
          label: '数量',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 140
        },
        {
          prop: 'inventoryQuantity',
          label: '库存数',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 140
        },
        {
          prop: 'sendTotalCount',
          label: '发货数量',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          prop: 'outboundTotalCount',
          label: '出库数量',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 140
        },
        {
          prop: 'returnTotalCount',
          label: '退货数量',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          prop: 'inventoryQuantity1',
          label: '库存状态',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 140,
          formatter: (_row, _column, cellValue) => {
            return _row.inventoryQuantity > 0 ? '有库存' : '无库存';
          }
        },
        {
          prop: 'saleTypeName',
          label: '销售类型',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 140
        },
        {
          prop: 'projectName',
          label: '项目名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 180
        },
        {
          prop: 'partaName',
          label: '客户名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 180
        },
        {
          prop: 'partaLinkName',
          label: '客户联系人',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 130
        },

        {
          prop: 'partaTel',
          label: '客户联系电话',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 130
        },
        {
          prop: 'partbName',
          label: '售出方名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 130
        },
        {
          prop: 'partbLinkName',
          label: '售出方联系人',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 130
        },
        {
          prop: 'partbTel',
          label: '售出方联系电话',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 130
        },
        {
          prop: 'payAmount',
          label: '金额(元)',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 170
        },
        {
          prop: 'arrivalWays',
          label: '到货方式',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 170,
          formatter: (_row, _column, cellValue) => {
            return _row.arrivalWays
              ? _row.arrivalWays
                  .split(',')
                  .map((val) => {
                    return val == 1 ? '一次性到货' : val == 2 ? '分批到货' : '';
                  })
                  .toString()
              : '';
          }
        },
        {
          prop: 'externalId',
          label: '是否推送',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          formatter: (_row, _column, cellValue) => {
            return _row.preOrderNo? '已推送' : '未推送';
          }
        },
        {
          prop: 'orderStatus',
          label: '审核状态',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 100,
          formatter: (_row, _column, cellValue) => {
            return reviewStatus[_row.orderStatus];
          }
        },

        {
          prop: 'createUserName',
          label: '创建人',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 80
        },
        {
          prop: 'createTime',
          label: '创建时间',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 170
        },
        {
          prop: 'reviewTime',
          label: '审核时间',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 170
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 280,
          align: 'center',
          resizable: false,
          slot: 'action',
          showOverflowTooltip: true,
          fixed: 'right'
        }
      ];
    }
  },
  methods: {
    getSummaries(param) {
        return getSummaries(
          param,
          ['productCount', 'sendTotalCount', 'outboundTotalCount', 'payAmount'],
          ' '
        );
      },
    async getInfo() {
      try {
        const res = await listOrganizations(); // 假设接口直接返回部门数组（如用户提供的示例数据）
        this.organizations = res; // 存储部门列表到状态中
        console.log('部门列表加载完成：', this.organizations);
      } catch (err) {
        console.error('加载部门列表失败：', err);
        this.organizations = []; // 异常时置空，避免匹配错误
      }
    },
    getToDoReminder() {
      getToDoReminder().then((res) => {
        this.toDoReminder = res;
      });
    },
    // 预销售编码输入框失焦回车事件
    handlePreOrderNoBlur(row) {
      updateOrderInfo({
        preOrderNo: row.preOrderNo
      })
        .then((res) => {
          console.log(res);
          this.$message.success('预销售编码更新成功');
        })
        .catch((err) => {});
    },
    finish(type, row) {
      if (type == 'single') {
        batchCompleted([row.id]).then((res) => {
          this.$message.success(res.message);
          this.reload();
        }).catch((err) => {});
      }
    },
    //更多菜单
    handleCommand(command, row) {
      if (command === 'invoice') {
        this.$refs.invoiceDialogRef.open('add', {}, [row.id]);
      }
      if (command === 'entrustedReceive') {
        this.addEntrustedReceiveFlag = true;
        this.$nextTick(() => {
          this.$refs.addEntrustedReceiveRef.open('add', {}, row.id);
        });
      }
      if (command === 'returnOrder') {
        this.$refs.addReturnGoodsRef.open('add', {});
      }
      if (command === 'saleOrderReminder') {
        saleOrderReminder(row.id).then((res) => {
          this.$message.success('催单成功');
        });
      }
      if (command === 'invoiceManage') {
        this.addOrEditDialogFlag1 = true;

        this.$nextTick(() => {
          this.$refs.addOrEditDialogRef.createInvoice1(row, 1, 3);
        });
      }
      // 冲差
      if (command === 'adjustment') {
        console.log(row);
        this.addAdjustDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.addAdjustDialogRef.open('add', row);
        });
      }
    },

    allPushBtn() {
      const dataId = this.selection.map((v) => v.id);
      saleOrderAdd(dataId).then((res) => {
        this.$message.success('推送成功！');
        this.reload();
      });
    },

    invoiceAll() {
      let partaIds = this.selection.map((item) => item.partaId);
      if (new Set(partaIds).size != 1) {
        return this.$message.warning('请选择相同客户的订单！');
      }
      let saleTypeS = this.selection.map((item) => item.saleType);
      if (new Set(saleTypeS).size != 1) {
        return this.$message.warning('请选择相同销售类型的订单！');
      }
      let processObj = this.selection.filter((item) => item.progress == 800);
      if (processObj?.length && this.isTotalCount == '1') {
        return this.$message.warning(
          '订单' +
            processObj.map((item) => item.orderNo).toString() +
            '已全部发货，不能创建发货单'
        );
      }
      if (
        this.selection.filter((item) => item.needProduce == 4)?.length &&
        this.selection.filter((item) => item.needProduce == 4)?.length !=
          this.selection.length
      ) {
        return this.$message.warning(
          '不定向订单不能与其它类型的订单一起创建发货单！'
        );
      }
      this.$refs.invoiceDialogRef.open(
        'add',
        {},
        this.selection.map((item) => item.id)
      );
    },
    //点击左边分类
    handleNodeClick(data, node) {
      // this.curNodeData = data;
      this.reload({ categoryId: data.id });
    },
    /* 表格数据源 */
    datasource({ page, limit, where, order }) {
      console.log('where~~~', where);
      if(where?.needProduces?.length){
        where['needProduces'] = where.needProduces.join(',');
      }
      if (this.contactData.id) {
        where['contactId'] = this.contactData.id;
      }

      // 构建进度列表参数
      const progressList = [];
      // 添加标签页进度筛选（如果不是'all'标签）
      if (this.activeName !== 'all') {
        progressList.push(this.activeName);
      }
      // 添加搜索条件中的进度筛选
      if (where?.progress) {
        progressList.push(where.progress);
      }
      
      // 构建请求参数
      this.params = {
        pageNum: page,
        size: limit,
        ...where
      };
      delete this.params.progress;
      // 仅当进度列表有值时添加到请求参数
      if (progressList.length > 0) {
        this.params.progressList = progressList.join(',');
      }
      return getTableList(this.params);
    },

    /* 刷新表格 */
    reload(where) {
      this.$refs.table.reload({ page: 1, where });
      this.getToDoReminder();
    },
    handleClick() {
      this.$refs.table.reload({
        page: 1,
        // where: { progress: this.activeName == 'all' ? '' : this.activeName }
      });
    },
    //新增编辑
    openEdit(type, row) {
      this.$refs.addDialogRef.open(type, row, row.id);
      this.$refs.addDialogRef.$refs.form &&
        this.$refs.addDialogRef.$refs.form.clearValidate();
    },

    //新增编辑新
    openEditNew(type, row) {
      this.$refs.addDialogNewRef.open(type, row, row.id);
      this.$refs.addDialogNewRef.$refs.form &&
        this.$refs.addDialogNewRef.$refs.form.clearValidate();
    },

    //批量删除
    allDelBtn() {
      if (this.selection.length === 0) return;
      let flag = this.selection.some((item) =>
        [1, 2].includes(item.orderStatus)
      );
      if (flag)
        return this.$message.warning('抱歉已审核、审核中的数据不能删除,请检查');
      this.delVisible = true;
    },

    //删除接口
    remove(delData) {
      deleteInformation(delData).then((res) => {
        this.$message.success('删除成功！');
        this.reload();
      });
    },

    //删除弹框确定
    commitBtn() {
      const dataId = this.selection.map((v) => v.id);
      this.remove(dataId);
    },

    //查看详情
    openorderDetail(row) {
      this.$refs.drawerRef.open(row);
    },
    async saleOrderSubmit(id) {
      this.$refs.addDialogRef && this.$refs.addDialogRef.cancel();
      // const data = await getSaleOrderDetail(id);

      this.processSubmitDialogFlag = true;
      let businessType =
        this.current.needProduce == 1
          ? '有客户生产性订单'
          : this.current.needProduce == 2
          ? '无客户生产性订单'
          : this.current.needProduce == 4
          ? '不定向订单'
          : '库存式订单';
      this.$nextTick(() => {
        let params = {
          businessId: this.current.id,
          businessKey: 'sales_order_approve',
          formCreateUserId: this.current.createUserId,
          variables: {
            businessCode: this.current.orderNo,
            businessName: this.current.partaName,
            businessType: businessType
          }
        };
        this.$refs.processSubmitDialogRef.init(params);
      });
    },
    async callBack() {
      if (!this.current.generatePurchase && !this.current.generateProduce) {
        return 0;
      }
      const code = saveOrderBomList({
        categoryDTOList: this.tableList || [],
        orderId: this.current.id
      });
      return code;
    },

    async saleOrderSubmitOrGenerate(res) {
      this.tableList = [];
      this.current = await getSaleOrderDetail(res.id);
      if (!this.current.generatePurchase && !this.current.generateProduce) {
        this.saleOrderSubmit(res.id);
      } else {
        const data = await getByRepeatBomAttribute(res.id);
        if (data && data.length) {
          this.$refs.bomDialogRef.open(data);
          return;
        }
        this.saleOrderSubmit(res.id);
      }
    },
    bomDialogSuccess(tableList) {
      this.tableList = tableList;
      // this.callBack()
      this.saleOrderSubmit(this.current.id);
    },
    //生成
    handleAutoGenerate(id, isAuto = false) {
      this.$refs.autogenerateDialogRef.init(id, isAuto);
    },
    //查看来源详情
    openRelationCodeDetail(row) {
      let data = {
        id: row.relationId
      };
      if (row.relationType == 1) {
        this.$refs.opportunityDetailRef.open(data);
      }
      if (row.relationType == 2) {
        this.$refs.quotationDetailRef.open(data);
      }
      if (row.relationType == 3) {
        this.$refs.contractDetailRef.open(data);
      }
    },
    uploadFile() {
      this.$refs.importDialogRef.open();
    },
    exportFn() {
      console.log(this.params);
      exportSaleorder(this.params);
    },
    handlePrint() {
      console.log(this.selection[0]);
      // if (this.selection.length > 1) return this.$message.warning('请选择一条');
      this.$refs.printTemplateHtRef.open(this.selection.map((v) => v.id));
    },
    handleRtPrint() {
      this.$refs.printTemplateRtRef.open(this.selection.map((v) => v.id));
    }
  }
};
</script>

<style lang="scss" scoped>
:deep .el-card__body {
  padding: 0;
}

:deep(.el-link--inner) {
  margin-left: 0px !important;
}

.sys-organization-list {
  height: calc(100vh - 264px);
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  overflow: auto;
}

.sys-organization-list :deep(.el-tree-node__content) {
  height: 40px;

  & > .el-tree-node__expand-icon {
    margin-left: 10px;
  }
}

.el-dropdown-link {
  cursor: pointer;
  color: var(--color-primary-5);
}

.el-icon-arrow-down {
  font-size: 12px;
}
:deep(.el-badge__content.is-fixed) {
  top: 4px;
}
/* 优化输入框在表格中的样式 */
:deep(.el-table .el-input__inner) {
  border-radius: 4px;
  height: 28px;
  line-height: 28px;
}
:deep(.el-table .el-input) {
  margin: 0;
}
</style>