<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="编码" prop="code">
            <el-input v-model="queryParams.code" placeholder="请输入编码" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="目标名称" prop="goalName">
            <el-input v-model="queryParams.goalName" placeholder="请输入目标名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期" prop="documentDate">
            <el-date-picker v-model="documentDateRange" type="daterange" value-format="yyyy-MM-dd"
              @change="setBeginAndEnd" align="right" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              placeholder="请选择单据日期" :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-tooltip class="item" effect="dark" :content="showSearch?'隐藏搜索':'显示搜索'" placement="top">
              <el-button type="warning" :icon="showSearch?'el-icon-caret-top':'el-icon-caret-bottom'" circle
                @click="showSearch = !showSearch"></el-button>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="年度" prop="annual">
            <el-date-picker v-model="queryParams.annual" type="year" value-format="yyyy" placeholder="选择年度" clearable
              @keyup.enter.native="handleQuery">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据状态" prop="status">
            <el-select v-model="queryParams.status" clearable>
              <el-option v-for="dict in dict.type.sys_status" :key="dict.value" :label="dict.label" :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="制单人" prop="creator">
            <el-popover-select-v2 v-model="queryParams.creator" title="制单人" valueKey="name" referName="CONTACTS_PARAM"
              :dataMapping="{ creatorCode: 'code', creator: 'name'}" :source.sync="queryParams" placeholder="请输入负责人">
            </el-popover-select-v2>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="部门" prop="dept">
            <el-popover-select-v2 v-model="queryParams.dept" title="部门" valueKey="name" referName="DEPT_PARAM"
              :dataMapping="{ deptId: 'id', dept: 'name'}" :source.sync="queryParams" placeholder="请输入部门"
              @keyup.enter.native="handleQuery">
            </el-popover-select-v2>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="目标类型" prop="goalCategory">
            <el-select v-model="queryParams.goalCategory" placeholder="请输入目标类型">
              <el-option
                v-for="item in [{ value: '销售区域', label: '销售区域' }, { value: '一级分类', label: '一级分类' }, { value: '二级分类', label: '二级分类' }]"
                :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="queryParams.goalCategory === '销售区域'" label="销售区域" prop="saleZone">
            <el-popover-select-v2 v-model="queryParams.saleZoneCode" title="销售区域" valueKey="name"
              referName="MK_SALESAREA_PARAM" :dataMapping="{ saleZoneCode: 'code', saleZone: 'name'}"
              :source.sync="queryParams" placeholder="请输入销售区域">
            </el-popover-select-v2>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="queryParams.goalCategory === '一级分类'" label="一级分类" prop="oneLevelClassify">
            <el-select v-model="queryParams.oneLevelClassify" size="mini" clearable placeholder="请输入一级分类"
              @focus="chooseTreeReferForQuery('MATERIALCLASSIFY_PARAM', false, '一级物料分类')" style="width: 200px">
              <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="queryParams.goalCategory === '二级分类'" label="二级分类" prop="twoLevelClassify">
            <el-select v-model="queryParams.twoLevelClassify" size="mini" clearable placeholder="请输入二级分类"
              @focus="chooseTreeReferForQuery('MATERIALCLASSIFY_PARAM', false, '二级物料分类')" style="width: 200px">
              <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8" style="float: right">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handleCommand">
          <el-button type="warning" plain icon="el-icon-download" size="mini">
            导出<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="export">导出</el-dropdown-item>
            <el-dropdown-item command="exportDetails">导出明细</el-dropdown-item>
            <el-dropdown-item command="exportZoneSum">导出区域目标汇总</el-dropdown-item>
            <el-dropdown-item command="exportCustomSum">导出客户目标汇总</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="annualSaleGoalMergeList" @selection-change="handleSelectionChange"
      @row-dblclick="useDoubleClick" v-horizontal-scroll max-height="560">
      <el-table-column label="编码" align="center" prop="code" width="180" />
      <el-table-column label="目标名称" align="center" prop="goalName" width="240" />
      <el-table-column label="单据日期" align="center" prop="documentDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.documentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年度" align="center" prop="annual" width="100" />
      <el-table-column show-overflow-tooltip label="状态" align="center" width="100" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="creator" width="180" />
      <el-table-column label="部门" align="center" prop="dept" width="180" />
      <el-table-column label="目标类型" align="center" prop="goalCategory" width="180" />
      <el-table-column label="目标值汇总（元）" align="center" prop="goalTotal" width="180" />
      <el-table-column label="销售区域" align="center" prop="saleZone" width="220" />
      <el-table-column label="一级分类" align="center" prop="oneLevelClassify" width="180" />
      <el-table-column label="二级分类" align="center" prop="twoLevelClassify" width="180" />
      <el-table-column label="备注" align="center" prop="notes" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="useDoubleClick(scope.row)">查看
          </el-button>
          <el-button v-if="scope.row.status == '0' || scope.row.status == '3'" size="mini" type="text"
            @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-if="scope.row.status == '0' || scope.row.status == '3'" size="mini" type="text"
            @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button v-if="scope.row.status == '0' || scope.row.status == '3'" size="mini" type="text"
            @click="handleSubmit(scope.row)">提交</el-button>
          <el-button v-if="scope.row.status == '1'" size="mini" type="text" @click="handleReback(scope.row)">收回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]" @pagination="getList" />

    <!-- 添加或修改年度销售目标明细对话框 -->
    <el-drawer :title="title" :visible.sync="open" direction="rtl" :before-close="handleClose" size="100%"
      v-horizontal-scroll>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="openStatus == 'see'" size="mini">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="编码后端自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="目标名称" prop="goalName">
              <el-input v-model="form.goalName" placeholder="目标名称后端自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据日期" prop="documentDate">
              <el-date-picker v-model="form.documentDate" type="date" placeholder="选择单据日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年度" prop="annual">
              <el-date-picker v-model="form.annual" type="year" placeholder="选择年度" value-format="yyyy">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="制单人" prop="creator">
              <el-popover-select-v2 v-model="form.creator" title="制单人" valueKey="name" referName="CONTACTS_PARAM"
                :dataMapping="{ creatorCode: 'code', creator: 'name'}" :source.sync="form" placeholder="请输入制单人">
              </el-popover-select-v2>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="dept">
              <el-popover-select-v2 v-model="form.dept" title="部门" valueKey="name" referName="DEPT_PARAM"
                :dataMapping="{ deptId: 'id', dept: 'name'}" :source.sync="form" placeholder="请输入部门">
              </el-popover-select-v2>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="目标分类" prop="goalCategory">
              <el-select v-model="form.goalCategory" placeholder="请选择" @change="changeGoalCategoryForm">
                <el-option v-for="item in goalCategoryList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="目标合计（元）" prop="goalTotal" label-width="120px">
              <el-input v-model="form.goalTotal" placeholder="目标值汇总自动计算" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="备注" prop="notes">
              <el-input v-model="form.notes" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item v-if="form.goalCategory === '销售区域'" label="销售区域" prop="saleZone">
              <el-popover-select-v2 v-model="form.saleZone" title="销售区域" valueKey="name" referName="MK_SALESAREA_PARAM"
                :dataMapping="{ saleZoneCode: 'code', saleZone: 'name'}" :source.sync="form" placeholder="请输入销售区域">
              </el-popover-select-v2>
            </el-form-item>
            <el-form-item v-if="form.goalCategory === '一级分类'" label="一级分类" prop="oneLevelClassify">
              <el-select v-model="form.oneLevelClassify" clearable
                @focus="chooseTreeReferForMain('MATERIALCLASSIFY_PARAM', false, '一级物料分类')" style="width: 200px">
                <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.goalCategory === '二级分类'" label="二级分类" prop="twoLevelClassify">
              <el-select v-model="form.twoLevelClassify" clearable
                @focus="chooseTreeReferForMain('MATERIALCLASSIFY_PARAM', false, '二级物料分类')" style="width: 200px">
                <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据状态" prop="type">
              <el-select v-model="form.status" placeholder="" disabled>
                <el-option v-for="dict in dict.type.sys_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div>
          <el-row :gutter="10" class="mb8" style="margin-left: 94%">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-folder-opened" size="mini" @click="clickMerge">合 并
              </el-button>
            </el-col>
          </el-row>
          <el-tabs v-model="activeName" @tab-click="getNewTwoArray">
            <el-tab-pane label="年销售目标合并明细" name="annualSaleGoalMergeDetails">
              <el-table max-height="560" show-summary :summary-method="getSummaries" v-loading="loading" size="mini"
                :data="annualSaleGoalMergeDetailsList" v-horizontal-scroll>
                <el-table-column label="序号" type="index" width="70" align="center" fixed />
                <el-table-column label="销售组织" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="annualSaleGoalMergeDetailsList[scope.$index].saleOrg" title="销售组织"
                      valueKey="name" referName="ORG_PARAM" disabled :dataMapping="{saleOrg: 'name'}"
                      :source.sync="annualSaleGoalMergeDetailsList[scope.$index]" placeholder="请输入销售组织">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="销售区域" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="annualSaleGoalMergeDetailsList[scope.$index].saleZone" title="销售区域"
                      valueKey="name" referName="MK_SALESAREA_PARAM" disabled :dataMapping="{saleZone: 'name'}"
                      :source.sync="annualSaleGoalMergeDetailsList[scope.$index]" placeholder="请输入销售区域">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="客户" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="annualSaleGoalMergeDetailsList[scope.$index].custom" title="客户"
                      valueKey="name" referName="CUSTOMER_PARAM" disabled :dataMapping="{custom: 'name'}"
                      :source.sync="annualSaleGoalMergeDetailsList[scope.$index]" placeholder="请输入客户">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="负责人" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="annualSaleGoalMergeDetailsList[scope.$index].creator" title="负责人"
                      valueKey="name" referName="CONTACTS_PARAM" disabled :dataMapping="{creator: 'name'}"
                      :source.sync="annualSaleGoalMergeDetailsList[scope.$index]" placeholder="请输入负责人">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="一级分类" align="center" width="220">
                  <template slot-scope="scope">
                    <el-select v-model="annualSaleGoalMergeDetailsList[scope.$index].oneLevelClassify" size="mini"
                      clearable
                      @focus="chooseTreeReferForDetails('MATERIALCLASSIFY_PARAM', false, '一级物料分类', scope.$index)"
                      style="width: 200px" disabled>
                      <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="二级分类" align="center" width="220">
                  <template slot-scope="scope">
                    <el-select v-model="annualSaleGoalMergeDetailsList[scope.$index].twoLevelClassify" size="mini"
                      clearable
                      @focus="chooseTreeReferForDetails('MATERIALCLASSIFY_PARAM', false, '二级物料分类', scope.$index)"
                      style="width: 200px" disabled>
                      <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="合计（元）" align="center" prop="totalGoal" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="annualSaleGoalMergeDetailsList[scope.$index].totalGoal" disabled></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="一月（元）" align="center" prop="januaryGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].januaryGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="二月（元）" align="center" prop="februaryGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].februaryGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="三月（元）" align="center" prop="marchGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].marchGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="四月（元）" align="center" prop="aprilGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].aprilGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="五月（元）" align="center" prop="mayGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].mayGoal" :precision="2" :step="0.1"
                      :min="0">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="六月（元）" align="center" prop="juneGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].juneGoal" :precision="2" :step="0.1"
                      :min="0">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="七月（元）" align="center" prop="julyGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].julyGoal" :precision="2" :step="0.1"
                      :min="0">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="八月（元）" align="center" prop="augustGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].augustGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="九月（元）" align="center" prop="septemberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].septemberGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="十月（元）" align="center" prop="octoberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].octoberGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="十一月（元）" align="center" prop="novemberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].novemberGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="十二月（元）" align="center" prop="decemberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number
                      @change="computeTotalDetails(scope.$index, annualSaleGoalMergeDetailsList[scope.$index])"
                      v-model="annualSaleGoalMergeDetailsList[scope.$index].decemberGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="区域目标汇总(年)" name="zoneGoalSum(year)">
              <el-table max-height="300" show-summary :summary-method="getSummaries" v-loading="loading"
                :data="areaDetailList" v-horizontal-scroll>
                <el-table-column label="序号" type="index" width="70" align="center" fixed />
                <el-table-column label="销售组织" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="areaDetailList[scope.$index].saleOrg" title="销售组织" valueKey="name"
                      referName="CUSTOMER_PARAM" disabled :dataMapping="{saleOrg: 'name'}"
                      :source.sync="areaDetailList[scope.$index]" placeholder="请输入销售组织">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="销售区域" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="areaDetailList[scope.$index].saleZone" title="销售区域" valueKey="name"
                      referName="CUSTOMER_PARAM" disabled :dataMapping="{saleZone: 'name'}"
                      :source.sync="areaDetailList[scope.$index]" placeholder="请输入销售区域">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="负责人" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="areaDetailList[scope.$index].creator" title="负责人" valueKey="name"
                      referName="CONTACTS_PARAM" disabled :dataMapping="{creator: 'name'}"
                      :source.sync="areaDetailList[scope.$index]" placeholder="请输入负责人">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="合计（元）" align="center" prop="totalGoal" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="areaDetailList[scope.$index].totalGoal" disabled></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="一月（元）" align="center" prop="januaryGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].januaryGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="二月（元）" align="center" prop="februaryGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].februaryGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="三月（元）" align="center" prop="marchGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].marchGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="四月（元）" align="center" prop="aprilGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].aprilGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="五月（元）" align="center" prop="mayGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].mayGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="六月（元）" align="center" prop="juneGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].juneGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="七月（元）" align="center" prop="julyGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].julyGoal" :precision="2" :step="0.1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="八月（元）" align="center" prop="augustGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].augustGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="九月（元）" align="center" prop="septemberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].septemberGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="十月（元）" align="center" prop="octoberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].octoberGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="十一月（元）" align="center" prop="novemberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].novemberGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="十二月（元）" align="center" prop="decemberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="areaDetailList[scope.$index].decemberGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="客户目标汇总(年)" name="customerGoalSum(year)">
              <el-table max-height="300" show-summary :summary-method="getSummaries" v-loading="loading"
                :data="customerDetailList" v-horizontal-scroll>
                <el-table-column label="序号" type="index" width="70" align="center" fixed />
                <el-table-column label="销售组织" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="customerDetailList[scope.$index].saleOrg" title="销售组织"
                      valueKey="name" referName="CUSTOMER_PARAM" disabled :dataMapping="{saleOrg: 'name'}"
                      :source.sync="customerDetailList[scope.$index]" placeholder="请输入销售组织">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="销售区域" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="customerDetailList[scope.$index].saleZone" title="销售区域"
                      valueKey="name" referName="CUSTOMER_PARAM" disabled :dataMapping="{saleZone: 'name'}"
                      :source.sync="customerDetailList[scope.$index]" placeholder="请输入销售区域">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="客户" align="center" width="180">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="customerDetailList[scope.$index].custom" title="客户" valueKey="name"
                      referName="CUSTOMER_PARAM" disabled :dataMapping="{custom: 'name'}"
                      :source.sync="customerDetailList[scope.$index]" placeholder="请输入客户">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="合计（元）" align="center" prop="totalGoal" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="customerDetailList[scope.$index].totalGoal" disabled></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="一月（元）" align="center" prop="januaryGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].januaryGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="二月（元）" align="center" prop="februaryGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].februaryGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="三月（元）" align="center" prop="marchGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].marchGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="四月（元）" align="center" prop="aprilGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].aprilGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="五月（元）" align="center" prop="mayGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].mayGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="六月（元）" align="center" prop="juneGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].juneGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="七月（元）" align="center" prop="julyGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].julyGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="八月（元）" align="center" prop="augustGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].augustGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="九月（元）" align="center" prop="septemberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].septemberGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="十月（元）" align="center" prop="octoberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].octoberGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="十一月（元）" align="center" prop="novemberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].novemberGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="十二月（元）" align="center" prop="decemberGoal" width="220">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="customerDetailList[scope.$index].decemberGoal" :precision="2"
                      :step="0.1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
          <div slot="footer" class="dialog-footer" style="margin-left: 88%; margin-top: 1%">
            <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
            <el-button @click="cancel" size="medium">返 回</el-button>
          </div>
        </div>
      </el-form>
    </el-drawer>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <TreeRefers ref="treeQuery" @doSubmit="selectionsToInputForQuery" :single="true" />
    <TreeRefers ref="treeMain" @doSubmit="selectionsToInputForMain" :single="true" />
    <TreeRefers ref="treeDetails" @doSubmit="selectionsToInputForDetails" :single="true" />
  </div>
</template>

<script>
  import {
    addAnnualSaleGoalMerge,
    delAnnualSaleGoalMerge,
    getAnnualSaleGoalMerge,
    listAnnualSaleGoalMerge,
    updateAnnualSaleGoalMerge,
    submit
  } from "@/api/business/spd/goal_management/annualSaleGoalMerge";
  import {
    mergeAnnualSaleMergeDetails,
    delAnnualSaleMergeDetails,
    getAnnualSaleMergeDetails
  } from "@/api/business/spd/goal_management/annualSaleMergeDetails"
  import {
    getToken
  } from "@/utils/auth";
  import {
    getSummary
  } from "@/api/business/spd/goal_management/commonWays";
  import {
    rollBack
  } from "@/api/business/spd/goal_management/publicInterface";

  // 树形参照
  import TreeRefers from '@/components/Refers/treeRefer.vue'
  import ElPopoverSelectV2 from "@/components/popover-select-v2"
  import log from "../../../monitor/job/log";

  export default {
    name: "AnnualSaleGoalMerge",
    components: {
      TreeRefers,
      ElPopoverSelectV2
    },
    dicts: ["sys_status", "oa_templete_id"],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: false,
        // 总条数
        total: 0,
        // 年度销售目标明细表格数据
        annualSaleGoalMergeList: null,
        annualSaleGoalMergeDetailsList: null,
        areaDetailList: null,
        customerDetailList: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          code: null,
          goalName: null,
          documentDate: null,
          annual: null,
          creatorCode: null,
          creator: null,
          deptId: null,
          dept: null,
          goalCategory: null,
          goalTotal: null,
          notes: null,
          status: null,
          delFlag: null,
          saleZoneCode: null,
          saleZone: null,
          oneLevelClassifyCode: null,
          oneLevelClassify: null,
          twoLevelClassifyCode: null,
          twoLevelClassify: null,
          params: {
            beginTime: null,
            endTime: null
          }
        },
        documentDateRange: null,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        // 表单参数
        form: {
          id: null,
          code: null,
          goalName: null,
          documentDate: null,
          annual: null,
          creatorCode: null,
          creator: null,
          deptId: null,
          dept: null,
          goalCategory: null,
          goalTotal: null,
          notes: null,
          status: null,
          delFlag: null,
          saleZoneCode: null,
          saleZone: null,
          oneLevelClassifyCode: null,
          oneLevelClassify: null,
          twoLevelClassifyCode: null,
          twoLevelClassify: null,
          annualGoalMergeDetailsList: null,
          oldAnnualGoalMergeDetailsList: null
        },
        formDetails: {
          id: null,
          mergeCode: null,
          saleOrg: null,
          saleZone: null,
          custom: null,
          creator: null,
          oneLevelClassifyCode: null,
          oneLevelClassify: null,
          twoLevelClassifyCode: null,
          twoLevelClassify: null,
          goalSum: null,
          januaryGoal: null,
          februaryGoal: null,
          marchGoal: null,
          aprilGoal: null,
          mayGoal: null,
          juneGoal: null,
          julyGoal: null,
          augustGoal: null,
          septemberGoal: null,
          octoberGoal: null,
          novemberGoal: null,
          decemberGoal: null,
          delFlag: null
        },
        // 表单校验
        rules: {
          documentDate: [{
            required: true,
            message: '单据日期不能为空',
            trigger: 'blur'
          }],
          annual: [{
            required: true,
            message: '年度不能为空',
            trigger: 'blur'
          }],
          creator: [{
            required: true,
            message: '制单人不能为空',
            trigger: 'blur'
          }],
          dept: [{
            required: true,
            message: '部门不能为空',
            trigger: 'blur'
          }],
          goalCategory: [{
            required: true,
            message: '目标类型不能为空',
            trigger: 'blur'
          }],
          saleZone: [],
          oneLevelClassify: [],
          twoLevelClassify: []
        },
        // 树形参照
        referCondition: {
          type: '',
          isPage: true,
          title: '',
          index: null
        },
        classOptions: [],
        // 目标分类
        goalCategoryList: [{
          label: '销售区域',
          value: '销售区域'
        }, {
          label: '一级分类',
          value: '一级分类'
        }, {
          label: '二级分类',
          value: '二级分类'
        }],
        activeName: 'annualSaleGoalMergeDetails',
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/goal_management/annualSaleGoalMerge/importData"
        },
        //打开状态
        openStatus: null,
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询年度销售目标明细列表 */
      getList() {
        this.loading = true;
        listAnnualSaleGoalMerge(this.queryParams).then(response => {
          this.annualSaleGoalMergeList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.annualSaleGoalMergeList.forEach(item => {
            item.goalTotal = item.goalTotal.toFixed(2);
          })
        });
      },
      getListDetails() {
        this.loading = true;
        getAnnualSaleMergeDetails(this.form.id).then(response => {
          console.log(response);
          this.annualSaleGoalMergeDetailsList = response.data;
          this.computeTotal()
          this.form.annualGoalMergeDetailsList = this.annualSaleGoalMergeDetailsList
          updateAnnualSaleGoalMerge(this.form).then(response => {
            this.$modal.msgSuccess("目标值汇总修改成功");
          });
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          code: null,
          goalName: null,
          documentDate: null,
          annual: null,
          creatorCode: null,
          creator: null,
          deptId: null,
          dept: null,
          goalCategory: null,
          goalTotal: null,
          notes: null,
          status: null,
          delFlag: null,
          saleZoneCode: null,
          saleZone: null,
          oneLevelClassifyCode: null,
          oneLevelClassify: null,
          twoLevelClassifyCode: null,
          twoLevelClassify: null,
          annualGoalMergeDetailsList: null,
          oldAnnualGoalMergeDetailsList: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          code: null,
          goalName: null,
          documentDate: null,
          annual: null,
          creatorCode: null,
          creator: null,
          deptId: null,
          dept: null,
          goalCategory: null,
          goalTotal: null,
          notes: null,
          status: null,
          delFlag: null,
          saleZoneCode: null,
          saleZone: null,
          oneLevelClassifyCode: null,
          oneLevelClassify: null,
          twoLevelClassifyCode: null,
          twoLevelClassify: null,
          params: {
            beginTime: null,
            endTime: null
          }
        }
        this.documentDateRange = null
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.openStatus = 'edit';
        this.reset();
        this.annualSaleGoalMergeDetailsList = []
        this.areaDetailList = []
        this.customerDetailList = []
        this.activeName = 'annualSaleGoalMergeDetails'
        this.open = true;
        this.title = "添加--年度销售目标合并明细";
        this.form.documentDate = new Date().getFullYear().toString() + '-' + (new Date().getMonth() + 1).toString()
          .padStart(2, '0') + '-' + new Date().getDate().toString().padStart(2, '0')
        this.form.annual = new Date().getFullYear().toString()
        this.form.creatorCode = this.$store.state.user.name
        this.form.creator = this.$store.state.user.nickName
        this.form.deptId = this.$store.state.user.deptId
        this.form.dept = this.$store.state.user.deptName
      },
      handleAddDetails() {
        if (this.activeName !== 'annualSaleGoalMergeDetails') {
          return this.$message.error('当前标签不是‘年度销售目标合并明细’')
        }
        let list = {
          id: null,
          mergeCode: null,
          saleOrg: null,
          saleZone: null,
          custom: null,
          creator: null,
          oneLevelClassifyCode: null,
          oneLevelClassify: null,
          twoLevelClassifyCode: null,
          twoLevelClassify: null,
          goalSum: null,
          januaryGoal: null,
          februaryGoal: null,
          marchGoal: null,
          aprilGoal: null,
          mayGoal: null,
          juneGoal: null,
          julyGoal: null,
          augustGoal: null,
          septemberGoal: null,
          octoberGoal: null,
          novemberGoal: null,
          decemberGoal: null,
          delFlag: null
        }
        this.annualSaleGoalMergeDetailsList.push(list)
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.openStatus = 'edit';
        this.reset();
        const id = row.id || this.ids
        this.activeName = 'annualSaleGoalMergeDetails'
        this.areaDetailList = []
        this.customerDetailList = []
        getAnnualSaleGoalMerge(id).then(response => {
          console.log(response);
          this.form = response.data;
          this.form.goalTotal = this.form.goalTotal.toFixed(2)
          for (const element of this.form.annualGoalMergeDetailsList) {
            element.totalGoal = element.totalGoal.toFixed(2)
          }
          this.annualSaleGoalMergeDetailsList = JSON.parse(JSON.stringify(this.form.annualGoalMergeDetailsList))
          this.open = true;
          this.title = "修改--年度销售目标合并明细";
        });
      },
      //双击行
      useDoubleClick(row) {
        this.openStatus = 'see';
        this.reset();
        const id = row.id || this.ids
        this.activeName = 'annualSaleGoalMergeDetails'
        this.areaDetailList = []
        this.customerDetailList = []
        getAnnualSaleGoalMerge(id).then(response => {
          console.log(response);
          this.form = response.data;
          this.form.goalTotal = this.form.goalTotal.toFixed(2)
          for (const element of this.form.annualGoalMergeDetailsList) {
            element.totalGoal = element.totalGoal.toFixed(2)
          }
          this.annualSaleGoalMergeDetailsList = JSON.parse(JSON.stringify(this.form.annualGoalMergeDetailsList))
          this.open = true;
          this.title = "查看--年度销售目标合并明细";
        });
      },
      // 复制按钮操作
      handleCopy(id) {
        this.openStatus = 'edit';
        this.reset()
        this.annualSaleGoalMergeDetailsList = []
        this.areaDetailList = []
        this.customerDetailList = []
        this.activeName = 'annualSaleGoalMergeDetails'
        getAnnualSaleGoalMerge(id).then(response => {
          this.form = response.data
          this.form.id = null
          this.form.code = null
          this.title = "添加--年度销售目标合并明细";
          this.form.documentDate = new Date().getFullYear().toString() + '-' + (new Date().getMonth() + 1)
            .toString().padStart(2, '0') + '-' + new Date().getDate().toString().padStart(2, '0')
          this.form.annual = new Date().getFullYear().toString()
          this.form.goalTotal = 0
          this.form.goalTotal = this.form.goalTotal.toFixed(2)
          this.open = true
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              this.form.annualGoalMergeDetailsList = JSON.parse(JSON.stringify(this.annualSaleGoalMergeDetailsList))
              console.log(this.form);
              updateAnnualSaleGoalMerge(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.annualGoalMergeDetailsList = this.annualSaleGoalMergeDetailsList
              this.form.status = '0'
              console.log(this.form);
              addAnnualSaleGoalMerge(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除年度销售目标单据编号为"' + row.code + '"的数据项？').then(function () {
          return delAnnualSaleGoalMerge(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleDeleteDetails(index, row) {
        if (this.form.id === null) { // 新增
          this.annualSaleGoalMergeDetailsList.splice(index, 1)
          this.computeTotal()
        } else { // 修改
          if (row.id !== null) {
            this.$modal.confirm('是否确认删除年度销售目标明细序号为"' + (index + 1) + '"的数据项？').then(function () {
              return delAnnualSaleMergeDetails(row.id);
            }).then(() => {
              this.getListDetails();
              this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
          } else {
            this.annualSaleGoalMergeDetailsList.splice(index, 1)
            this.$message.success('删除成功')
            this.computeTotal()
          }
        }
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('goal_management/annualSaleGoalMerge/export', {
          ...this.queryParams
        }, `annualSaleGoalMerge_${new Date().getTime()}.xlsx`)
      },
      handleExportDetails() {
        this.download('goal_management/annualSaleMergeDetails/export', {
          ...this.queryParams
        }, `annualSaleMergeDetails_${new Date().getTime()}.xlsx`)
      },
      // 导出区域目标汇总
      handleExportZoneSum() {
        this.download('goal_management/annualSaleMergeDetails/exportZoneSum', {
          ...this.queryParams
        }, `zoneSum_${new Date().getTime()}.xlsx`)
      },
      // 导出客户目标汇总
      handleExportCustomSum() {
        this.download('goal_management/annualSaleMergeDetails/exportCustomSum', {
          ...this.queryParams
        }, `customSum_${new Date().getTime()}.xlsx`)
      },
      // 树形参照
      chooseTreeReferForQuery(type, isPage, title) {
        this.referCondition.type = type
        this.referCondition.isPage = isPage
        this.referCondition.title = title
        this.$refs.treeQuery.init(this.referCondition)
      },
      selectionsToInputForQuery(selection) {
        this.classOptions = selection;
        if (this.referCondition.title === '一级物料分类') {
          if (this.classOptions[0].code.length > 2) {
            return this.$message.info('请在一级分类下选择');
          }
          this.queryParams.oneLevelClassifyCode = selection[0].code
          this.queryParams.oneLevelClassify = selection[0].name
        } else if (this.referCondition.title === '二级物料分类') {
          if (this.classOptions[0].code.lastIndexOf("-") == 3 || this.classOptions[0].code.indexOf("90") == 0) {
            this.queryParams.twoLevelClassifyCode = selection[0].code
            this.queryParams.twoLevelClassify = selection[0].name
          } else {
            return this.$message.info('请在二级分类下选择')
          }
        }
      },
      chooseTreeReferForMain(type, isPage, title) {
        this.referCondition.type = type
        this.referCondition.isPage = isPage
        this.referCondition.title = title
        this.$refs.treeMain.init(this.referCondition)
      },
      selectionsToInputForMain(selection) {
        this.classOptions = selection;
        if (this.referCondition.title === '一级物料分类') {
          if (this.classOptions[0].code.length > 2) {
            return this.$message.info('请在一级分类下选择');
          }
          this.form.oneLevelClassifyCode = selection[0].code
          this.form.oneLevelClassify = selection[0].name
        } else if (this.referCondition.title === '二级物料分类') {
          if (this.classOptions[0].code.lastIndexOf("-") == 3 || this.classOptions[0].code.indexOf("90") == 0) {
            this.form.twoLevelClassifyCode = selection[0].code
            this.form.twoLevelClassify = selection[0].name
          } else {
            return this.$message.info('请在二级分类下选择')
          }
        }
      },
      chooseTreeReferForDetails(type, isPage, title, index) {
        this.referCondition.type = type
        this.referCondition.isPage = isPage
        this.referCondition.title = title
        this.referCondition.index = index
        this.$refs.treeDetails.init(this.referCondition)
      },
      selectionsToInputForDetails(selection) {
        this.classOptions = selection;
        if (this.referCondition.title === '一级物料分类') {
          if (this.classOptions[0].code.length > 2) {
            return this.$message.info('请在一级分类中选择')
          }
          if (selection.code !== this.annualSaleGoalMergeDetailsList[this.referCondition.index].oneLevelClassifyCode) {
            this.annualSaleGoalMergeDetailsList[this.referCondition.index].twoLevelClassifyCode = null
            this.annualSaleGoalMergeDetailsList[this.referCondition.index].twoLevelClassify = null
          }
          this.annualSaleGoalMergeDetailsList[this.referCondition.index].oneLevelClassifyCode = selection.code
          this.annualSaleGoalMergeDetailsList[this.referCondition.index].oneLevelClassify = selection.name
        } else if (this.referCondition.title === '二级物料分类') {
          if (this.classOptions[0].code.lastIndexOf("-") == 3 || this.classOptions[0].code.indexOf("90") == 0) {
            return this.$message.info('请在二级分类中选择')
          } else if (selection.code[0] !== this.annualSaleGoalMergeDetailsList[this.referCondition.index]
            .oneLevelClassifyCode) {
            return this.$message.error('所选择的二级物料分类不属于一级分类')
          }
          this.annualSaleGoalMergeDetailsList[this.referCondition.index].twoLevelClassifyCode = selection.code
          this.annualSaleGoalMergeDetailsList[this.referCondition.index].twoLevelClassify = selection.name
        }
      },
      changeGoalCategoryForm() {
        let condition = this.form.goalCategory
        if (condition === '销售区域') {
          this.form.oneLevelClassifyCode = null
          this.form.oneLevelClassify = null
          this.form.twoLevelClassifyCode = null
          this.form.twoLevelClassify = null
          this.rules.saleZone = [{
            required: true,
            message: '销售区域不能为空',
            trigger: 'blur'
          }]
          this.rules.oneLevelClassify = []
          this.rules.twoLevelClassify = []
        } else if (condition === '一级分类') {
          this.form.saleZoneCode = null
          this.form.saleZone = null
          this.form.twoLevelClassifyCode = null
          this.form.twoLevelClassify = null
          this.rules.saleZone = []
          this.rules.oneLevelClassify = [{
            required: true,
            message: '一级分类不能为空',
            trigger: 'blur'
          }]
          this.rules.twoLevelClassify = []
        } else if (condition === '二级分类') {
          this.form.saleZoneCode = null
          this.form.saleZone = null
          this.form.oneLevelClassifyCode = null
          this.form.oneLevelClassify = null
          this.rules.saleZone = []
          this.rules.oneLevelClassify = []
          this.rules.twoLevelClassify = [{
            required: true,
            message: '二级分类不能为空',
            trigger: 'blur'
          }]
        } else {
          this.form.saleZoneCode = null
          this.form.saleZone = null
          this.form.oneLevelClassifyCode = null
          this.form.oneLevelClassify = null
          this.form.twoLevelClassifyCode = null
          this.form.twoLevelClassify = null
          this.rules.saleZone = []
          this.rules.oneLevelClassify = []
          this.rules.twoLevelClassify = []
        }
      },
      // 关闭抽屉
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      // 复制明细
      handleCopyDetails(row) {
        let list = {
          id: null,
          mergeCode: row.mergeCode,
          saleOrg: row.saleOrg,
          saleZone: row.saleZone,
          custom: row.custom,
          creator: row.creator,
          oneLevelClassifyCode: row.oneLevelClassifyCode,
          oneLevelClassify: row.oneLevelClassify,
          twoLevelClassifyCode: row.twoLevelClassifyCode,
          twoLevelClassify: row.twoLevelClassify,
          totalGoal: row.totalGoal,
          januaryGoal: row.januaryGoal,
          februaryGoal: row.februaryGoal,
          marchGoal: row.marchGoal,
          aprilGoal: row.aprilGoal,
          mayGoal: row.mayGoal,
          juneGoal: row.juneGoal,
          julyGoal: row.julyGoal,
          augustGoal: row.augustGoal,
          septemberGoal: row.septemberGoal,
          octoberGoal: row.octoberGoal,
          novemberGoal: row.novemberGoal,
          decemberGoal: row.decemberGoal,
          delFlag: row.delFlag
        }
        this.annualSaleGoalMergeDetailsList.push(list)
        this.computeTotal()
      },
      // 计算子表合计
      computeTotalDetails(index, row) {
        let array = [row.januaryGoal, row.februaryGoal, row.marchGoal, row.aprilGoal, row.mayGoal, row.juneGoal, row
          .julyGoal, row.augustGoal, row.septemberGoal, row.octoberGoal, row.novemberGoal, row.decemberGoal
        ]
        let sum = 0
        for (const element of array) {
          sum = (sum * 1000000 + element * 1000000) / 1000000
        }
        this.annualSaleGoalMergeDetailsList[index].totalGoal = sum
        this.computeTotal()
      },
      // 计算主表合计
      computeTotal() {
        let list = this.annualSaleGoalMergeDetailsList
        let sum = 0
        for (const listElement of list) {
          if (listElement.totalGoal === null) {
            listElement.totalGoal = 0
          }
          sum = (sum * 1000000 + listElement.totalGoal * 1000000) / 1000000
        }
        this.form.goalTotal = sum.toFixed(2)
      },
      getSummaries(param) {
        return getSummary(param)
      },
      // 合并数据
      clickMerge() {
        if (this.form.id !== null) {
          this.form.oldAnnualGoalMergeDetailsList = JSON.parse(JSON.stringify(this.annualGoalMergeDetailsList))
        }
        if (this.activeName !== 'annualSaleGoalMergeDetails') {
          return this.$message.error('当前标签不是年销售目标合并明细')
        }
        let query = JSON.parse(JSON.stringify(this.form))
        query.annualGoalMergeDetailsList = []
        console.log(query);
        if (query.goalCategory === null || query.goalCategory === '') {
          return this.$message.error('请输入目标分类')
        } else if (query.goalCategory === '销售区域') {
          if (query.saleZone === null) {
            return this.$message.error('请输入销售区域')
          }
        } else if (query.goalCategory === '一级分类') {
          if (query.oneLevelClassify === null) {
            return this.$message.error('请输入一级分类')
          }
        } else if (query.goalCategory === '二级分类') {
          if (query.twoLevelClassify === null) {
            return this.$message.error('请输入二级分类')
          }
        }
        mergeAnnualSaleMergeDetails(query).then(response => {
          console.log(response);
          if (response.data.consolidatedDetail.length > 0) {
            // for (const consolidatedDetail of response.data.consolidatedDetail) {
            //   consolidatedDetail.totalGoal = consolidatedDetail.totalGoal.toFixed(2)
            // }
            this.annualSaleGoalMergeDetailsList = response.data.consolidatedDetail
            this.computeTotal()
          } else {
            return this.$message.warning('未查到相关数据')
          }
        })
      },
      // 获得区域目标汇总or客户目标汇总
      getNewTwoArray() {
        let arr = JSON.parse(JSON.stringify(this.annualSaleGoalMergeDetailsList))
        // 如果子表标签是annualSaleGoalMergeDetails 或者 主表的目标分类是“销售区域”
        if (this.activeName === 'annualSaleGoalMergeDetails') {
          this.areaDetailList = null
          this.customerDetailList = null
          return
        }
        // 根据某三个属性进行合并并相加totalGoal的函数
        const mergeAndSumTotalGoal = (array) => {
          return Array.from(array.reduce((map, obj) => {
            let key = null
            if (this.activeName === 'zoneGoalSum(year)') {
              key = `${obj.saleOrg}-${obj.saleZone}-${obj.creator}`
            } else if (this.activeName === 'customerGoalSum(year)') {
              key = `${obj.saleOrg}-${obj.saleZone}-${obj.custom}`
            }
            console.log(key);
            if (map.has(key)) {
              const existingObj = map.get(key)
              existingObj.totalGoal = parseFloat(existingObj.totalGoal)
              existingObj.totalGoal += parseFloat(obj.totalGoal)
              existingObj.totalGoal = existingObj.totalGoal.toFixed(2)
              existingObj.januaryGoal += obj.januaryGoal
              existingObj.februaryGoal += obj.februaryGoal
              existingObj.marchGoal += obj.marchGoal
              existingObj.aprilGoal += obj.aprilGoal
              existingObj.mayGoal += obj.mayGoal
              existingObj.juneGoal += obj.juneGoal
              existingObj.julyGoal += obj.julyGoal
              existingObj.augustGoal += obj.augustGoal
              existingObj.septemberGoal += obj.septemberGoal
              existingObj.octoberGoal += obj.octoberGoal
              existingObj.novemberGoal += obj.novemberGoal
              existingObj.decemberGoal += obj.decemberGoal
            } else {
              map.set(key, {
                ...obj
              })
            }
            return map
          }, new Map()).values())
        }
        // 调用合并函数
        const mergedArray = mergeAndSumTotalGoal(arr)
        if (this.activeName === 'zoneGoalSum(year)') {
          this.areaDetailList = mergedArray
        } else if (this.activeName === 'customerGoalSum(year)') {
          this.customerDetailList = mergedArray
        }
      },
      setBeginAndEnd() {
        let array = this.documentDateRange
        if (array !== null) {
          this.queryParams.params.beginTime = array[0]
          this.queryParams.params.endTime = array[1]
        } else {
          this.queryParams.params.beginTime = null
          this.queryParams.params.endTime = null
        }
      },
      handleCommand(command) {
        // 执行对应的功能
        if (command === 'export') {
          console.log('导出主表');
          this.handleExport()
        } else if (command === 'exportDetails') {
          console.log('导出明细');
          this.handleExportDetails()
        } else if (command === 'exportZoneSum') {
          console.log('导出区域目标汇总')
          this.handleExportZoneSum()
        } else if (command === 'exportCustomSum') {
          console.log('导出客户目标汇总')
          this.handleExportCustomSum()
        }
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.open = true;
        this.upload.title = "年销售目标合并导入";
        this.upload.url = process.env.VUE_APP_BASE_API + "goal_management/annualSaleGoalMerge/importData"
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('goal_management/annualSaleGoalMerge/importTemplate', {},
          `annualSaleGoalMerge_${new Date().getTime()}.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        console.log(response);
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response
          .msg + "</div>", "导入结果", {
            dangerouslyUseHTMLString: true
          });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      //提交
      async handleSubmit(row) {
        this.$modal.loading("提交中...");
        try {
          const {
            msg,
            code
          } = await submit(row.id);
          if (code === 200) {
            this.$modal.notifySuccess("提交成功");
            this.$modal.closeLoading();
            row.status = '1'
            // this.getList(this.queryParams)
          }
        } catch (err) {
          console.error(err);
          this.$modal.closeLoading();
        }
      },
      //收回
      handleReback(row) {
        this.$modal.loading("收回中...");
        let params = {
          billCode: row.code,
          fdId: row.flowId,
          fdTemplateId: this.dict.type.oa_templete_id.find(item => {
            return item.label == "销售目标"
          }).value,
          billMaker: row.createBy,
          type: "2"
        }
        rollBack(params).then(res => {
          if (res.code === 200) {
            this.$modal.notifySuccess("收回成功");
            this.$modal.closeLoading();
            this.getList(this.queryParams)
          }
        }).catch(err => {
          this.$modal.closeLoading();
        })
      },
    }
  };

</script>
