<template>
  <div class="app-container">
    <div v-if="isList">
      <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" value-format="yyyy-MM-dd" @change="setBeginAndEnd"
                type="daterange" align="right" range-separator="至" start-placeholder="开始日期" end-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="custom" v-if="isDept && !isJiwei">
              <el-popover-tree-select v-model="queryParams.custom" valueKey='name' title="客户" referName="PROFITCENTER"
                :dataMapping="{ customCode: 'code', custom: 'name'}" :source.sync="queryParams" placeholder="请输入客户"
                @keyup.enter.native="handleQuery">
              </el-popover-tree-select>
            </el-form-item>
            <el-form-item label="客户" prop="custom" v-if="!(isDept && !isJiwei)">
              <el-popover-select-v2 v-model="queryParams.custom" title="客户" valueKey="name" referName="CUSTOMER_PARAM"
                :dataMapping="{ customCode: 'code', custom: 'name'}" :source.sync="queryParams" placeholder="请输入客户"
                @keyup.enter.native="handleQuery">
              </el-popover-select-v2>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售区域" prop="saleZone">
              <el-popover-select-v2 v-model="queryParams.saleZone" title="销售区域" valueKey="name"
                referName="MK_SALESAREA_PARAM" :dataMapping="{ saleZoneCode: 'code', saleZone: 'name'}"
                :source.sync="queryParams" placeholder="请输入销售区域" @keyup.enter.native="handleQuery">
              </el-popover-select-v2>
            </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="请输入制单人"
                @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="dept">
              <el-popover-select-v2 v-model="queryParams.dept" title="部门" valueKey="name" referName="DEPT_PARAM"
                :dataMapping="{ deptCode: 'id', dept: 'name'}" :source.sync="queryParams" placeholder="请输入部门"
                @keyup.enter.native="handleQuery">
              </el-popover-select-v2>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据状态" prop="status">
              <el-select size="mini" 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-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-menu>
          </el-dropdown>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="monthSaleGoalList" @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 label="客户" align="center" prop="custom" width="180" />
        <el-table-column label="销售区域" align="center" prop="saleZone" width="180" />
        <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="goalSum" width="180" />
        <el-table-column label="备注" align="center" prop="notes" width="180" />
        <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" 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" />
    </div>

    <!-- <el-drawer :title="title" :visible.sync="open" direction="rtl" :before-close="handleClose" size="100%"
      v-horizontal-scroll> -->
    <div v-if="!isList">
      <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 clearable v-model="form.documentDate" type="date" value-format="yyyy-MM-dd"
                @change="setItemMonthly" placeholder="请选择单据日期">
              </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" value-format="yyyy" placeholder="选择年度">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户" prop="custom" v-if="isDept && !isJiwei">
              <el-popover-tree-select v-model="form.custom" valueKey='name' title="客户" referName="PROFITCENTER"
                :dataMapping="{ customCode: 'code', custom: 'name'}" :source.sync="form" placeholder="请输入客户">
              </el-popover-tree-select>
            </el-form-item>
            <el-form-item label="客户" prop="custom" v-if="!(isDept && !isJiwei)">
              <el-popover-select-v2 v-model="form.custom" title="客户" valueKey="name" referName="CUSTOMER_PARAM"
                :dataMapping="{ customCode: 'code', custom: 'name'}" :source.sync="form" placeholder="请输入客户">
              </el-popover-select-v2>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item 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-col>
          <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="{ deptCode: 'code', dept: 'name'}" :source.sync="form" placeholder="请输入部门">
              </el-popover-select-v2>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="销售目标合计（元）" prop="goalSum" label-width="150px">
              <el-input v-model="form.goalSum" placeholder="目标合计自动计算" disabled />
            </el-form-item>
          </el-col>
          <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 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-col :span="6">
            <el-form-item label="时间范围" prop="materialRange">
              <el-select v-model="materialRange" placeholder="请选择获取物料的时间范围">
                <el-option v-for="item in dateOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div>
          <el-row :gutter="10" class="mb8" style="margin-left: 67%">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="getMaterialList">查询物料
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleTemplateDownload">模板下载
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-upload ref="upload" action="" :http-request="handleImport">
                <el-button size="mini" type="primary">导入明细</el-button>
              </el-upload>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddDetails">增行</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-edit-outline" size="mini"
                @click="dialogUpdateMore.dialogFormVisible = true">批量修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="batchRemove">批量删除</el-button>
            </el-col>
          </el-row>
          <el-tabs v-model="activeName">
            <el-tab-pane label="月销售/月利润目标明细" name="monthSaleGoalDetails">
              <el-table max-height="560" show-summary :summary-method="getSummaries" v-loading="loading" size="mini"
                :data="monthSaleGoalDetailsList" @selection-change="handleSelectionChange" v-horizontal-scroll>
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" type="index" width="70" align="center" fixed />
                <!-- <el-table-column label="销售组织" align="center" width="180" :render-header="addRedStar">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="monthSaleGoalDetailsList[scope.$index].saleOrg" title="销售组织"
                      valueKey="name" referName="ORG_PARAM" :dataMapping="{ saleOrgCode: 'code', saleOrg: 'name'}"
                      :source.sync="monthSaleGoalDetailsList[scope.$index]" placeholder="请输入销售组织">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="销售区域" align="center" width="180" :render-header="addRedStar">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="monthSaleGoalDetailsList[scope.$index].saleZone" title="销售区域"
                      valueKey="name" referName="MK_SALESAREA_PARAM"
                      :dataMapping="{ saleZoneCode: 'code', saleZone: 'name'}"
                      :source.sync="monthSaleGoalDetailsList[scope.$index]" placeholder="请输入销售区域">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="客户" align="center" width="180" :render-header="addRedStar">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="monthSaleGoalDetailsList[scope.$index].custom" title="客户"
                      valueKey="name" referName="CUSTOMER_PARAM" :dataMapping="{ customCode: 'code', custom: 'name'}"
                      :source.sync="monthSaleGoalDetailsList[scope.$index]" placeholder="请输入客户">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="部门" align="center" width="180" :render-header="addRedStar">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="monthSaleGoalDetailsList[scope.$index].dept" title="部门"
                      valueKey="name" referName="DEPT_PARAM" :dataMapping="{ deptCode: 'code', dept: 'name'}"
                      :source.sync="monthSaleGoalDetailsList[scope.$index]" placeholder="请输入部门">
                    </el-popover-select-v2>
                  </template>
                </el-table-column>
                <el-table-column label="制单人" align="center" width="180" :render-header="addRedStar">
                  <template slot-scope="scope">
                    <el-popover-select-v2 v-model="monthSaleGoalDetailsList[scope.$index].creator" title="制单人"
                      valueKey="name" referName="CONTACTS_PARAM" :dataMapping="{ creatorCode: 'code', creator: 'name'}"
                      :source.sync="monthSaleGoalDetailsList[scope.$index]" placeholder="请输入制单人">
                    </el-popover-select-v2>
                  </template>
                </el-table-column> -->
                <el-table-column label="一级分类" align="center" min-width="200" :render-header="addRedStar">
                  <template slot-scope="scope">
                    <el-select v-model="monthSaleGoalDetailsList[scope.$index].oneLevelClassify" clearable
                      @focus="chooseTreeReferForMain('MATERIALCLASSIFY_PARAM', false, '一级物料分类', scope.$index)"
                      :disabled="!isDept">
                      <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.code" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="二级分类" align="center" min-width="200" :render-header="addRedStar">
                  <template slot-scope="scope">
                    <el-select v-model="monthSaleGoalDetailsList[scope.$index].twoLevelClassify" clearable
                      @focus="chooseTreeReferForMain('MATERIALCLASSIFY_PARAM', false, '二级物料分类', scope.$index)"
                      :disabled="!isDept">
                      <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.code" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="物料" align="center" min-width="220" :render-header="addRedStarChange">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" placement="top-start">
                      <div slot="content">{{ scope.row.memo }}</div>
                      <el-popover-select-v2 v-model="monthSaleGoalDetailsList[scope.$index].material" title="物料"
                        valueKey="name" referName="MATERIAL_PARAM"
                        @change="setClassify(scope.row.oneLevelClassify, scope.row.twoLevelClassify, monthSaleGoalDetailsList[scope.$index], scope.row)"
                        :dataMapping="{ materialCode: 'code', material: 'name', oneLevelClassify: 'oneClass', twoLevelClassify: 'twoClass',
                        specification: 'specification', packExplain: 'packExplain', model: 'model'}"
                        :source.sync="monthSaleGoalDetailsList[scope.$index]" placeholder="请输入物料">
                      </el-popover-select-v2>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column label="科室" align="center" min-width="200">
                  <template slot-scope="scope">
                    <el-select v-model.trim="monthSaleGoalDetailsList[scope.$index].department" placeholder="请选择科室"
                      filterable>
                      <el-option v-for="dict in dict.type.mk_bo_section" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="数量" align="center" prop="num" min-width="220">
                  <template slot-scope="scope">
                    <el-input-number v-model="monthSaleGoalDetailsList[scope.$index].num" :min="0"
                      @change="calculate(scope.row)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="月份" align="center" min-width="250">
                  <template slot-scope="scope">
                    <el-date-picker v-model="monthSaleGoalDetailsList[scope.$index].monthly" value-format="yyyy-MM"
                      disabled type="month" placeholder="选择月份">
                    </el-date-picker>
                  </template>
                </el-table-column>
                <el-table-column label="销售目标值（元）" align="center" prop="goalValue" min-width="220"
                  :render-header="addRedStar">
                  <template slot-scope="scope">
                    <el-input-number @change="computeTotal" v-model="monthSaleGoalDetailsList[scope.$index].goalValue"
                      :precision="2" :step="1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="利润目标值（元）" align="center" prop="profitTargetValue" min-width="220"
                  :render-header="addRedStar" v-if="isDept">
                  <template slot-scope="scope">
                    <el-input-number @change="computeTotal"
                      v-model="monthSaleGoalDetailsList[scope.$index].profitTargetValue" :precision="2" :step="1"
                      :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px"
                  fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteDetails(scope.row)">删除
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleCopyDetails(scope.row)">复制
                    </el-button>
                  </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" :disabled="false">返 回</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <!-- </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>
    <!-- 批量修改对话框-->
    <el-dialog title="批量修改" width="30%" :visible.sync="dialogUpdateMore.dialogFormVisible" append-to-body
      @closed="resetDialogUpdateMore">
      <el-form>
        <el-form-item label="修改项" label-width="100px">
          <el-select @change="changeDialogData" v-model="dialogUpdateMore.updateName" placeholder="请选择需要批量修改的字段">
            <el-option v-for="item in dialogUpdateMore.optionList" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="修改值" label-width="100px">
          <el-popover-select-v2 v-if="dialogUpdateMore.updateName === 1" v-model="dialogUpdateMore.updateData"
            title="销售组织" valueKey="name" referName="ORG_PARAM" :dataMapping="{updateData: 'name'}"
            :source.sync="dialogUpdateMore" placeholder="请输入销售组织">
          </el-popover-select-v2>
          <el-popover-select-v2 v-else-if="dialogUpdateMore.updateName === 2" v-model="dialogUpdateMore.updateData"
            title="销售区域" valueKey="name" referName="MK_SALESAREA_PARAM" :dataMapping="{updateData: 'name'}"
            :source.sync="dialogUpdateMore" placeholder="请输入销售区域">
          </el-popover-select-v2>
          <el-popover-select-v2 v-else-if="dialogUpdateMore.updateName === 3" v-model="dialogUpdateMore.updateData"
            title="客户" valueKey="name" referName="CUSTOMER_PARAM" :dataMapping="{updateData: 'name'}"
            :source.sync="dialogUpdateMore" placeholder="请输入客户">
          </el-popover-select-v2>
          <el-popover-select-v2 v-else-if="dialogUpdateMore.updateName === 4" v-model="dialogUpdateMore.updateData"
            title="部门" valueKey="name" referName="DEPT_PARAM" :dataMapping="{updateData: 'name'}"
            :source.sync="dialogUpdateMore" placeholder="请输入部门">
          </el-popover-select-v2>
          <el-popover-select-v2 v-else-if="dialogUpdateMore.updateName === 5" v-model="dialogUpdateMore.updateData"
            title="制单人" valueKey="name" referName="CONTACTS_PARAM" :dataMapping="{updateData: 'name'}"
            :source.sync="dialogUpdateMore" placeholder="请输入制单人">
          </el-popover-select-v2>
          <el-input v-else-if="dialogUpdateMore.updateName === 6" v-model="dialogUpdateMore.updateData"
            placeholder="请输入科室"></el-input>
          <el-date-picker v-else-if="dialogUpdateMore.updateName === 7" v-model="dialogUpdateMore.updateData"
            value-format="yyyy-MM" type="month" placeholder="选择月">
          </el-date-picker>
          <el-input v-else placeholder="请输入修改项" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogUpdateMoreSave">确 定</el-button>
      </div>
    </el-dialog>
    <TreeRefers ref="treeMain" @doSubmit="selectionsToInputForMain" :single="true" />
  </div>
</template>

<script>
  import {
    listMonthSaleGoal,
    getMonthSaleGoal,
    delMonthSaleGoal,
    addMonthSaleGoal,
    updateMonthSaleGoal,
    submit
  } from "@/api/business/spd/goal_management/monthSaleGoal";
  import {
    getMonthSaleGoalDetails,
    delMonthSaleGoalDetails,
    importData,
    getMaterialRangeList,
    getDeptIds
  } from "@/api/business/spd/goal_management/monthSaleGoalDetails"
  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"

  export default {
    name: "MonthSaleGoal",
    components: {
      TreeRefers,
      ElPopoverSelectV2,
      ElPopoverTreeSelect: () =>
        import("@/components/popover-tree-select/index.vue"),
    },
    dicts: ["sys_status", "oa_templete_id", "mk_bo_section"],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: false,
        // 总条数
        total: 0,
        // 月销售/月利润目标填报表格数据
        monthSaleGoalList: [],
        monthSaleGoalDetailsList: [],
        delMonthSaleGoalDetailsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          code: null,
          goalName: null,
          documentDate: null,
          annual: null,
          customCode: null,
          custom: null,
          saleZoneCode: null,
          saleZone: null,
          creatorCode: null,
          creator: null,
          deptCode: null,
          dept: null,
          goalSum: null,
          notes: null,
          status: 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,
          customCode: null,
          custom: null,
          saleZoneCode: null,
          saleZone: null,
          creatorCode: null,
          creator: null,
          deptCode: null,
          dept: null,
          goalSum: null,
          notes: null,
          status: null,
          monthDetailsList: null,
          isDept: null
        },
        formDetails: {
          id: null,
          code: null,
          saleOrg: null,
          saleZone: null,
          custom: null,
          dept: null,
          creator: null,
          oneLevelClassifyCode: null,
          oneLevelClassify: null,
          twoLevelClassifyCode: null,
          twoLevelClassify: null,
          materialCode: null,
          specification: null,
          packExplain: null,
          model: null,
          material: null,
          department: null,
          num: null,
          monthly: null,
          goalValue: null
        },
        // 表单校验
        rules: {
          documentDate: [{
            required: true,
            message: '单据日期不能为空',
            trigger: 'blur'
          }],
          annual: [{
            required: true,
            message: '年度不能为空',
            trigger: 'blur'
          }],
          custom: [{
            required: true,
            message: '客户不能为空',
            trigger: 'blur'
          }],
          saleZone: [{
            required: true,
            message: '销售区域不能为空',
            trigger: 'blur'
          }],
          creator: [{
            required: true,
            message: '制单人不能为空',
            trigger: 'blur'
          }],
          dept: [{
            required: true,
            message: '部门不能为空',
            trigger: 'blur'
          }]
        },
        // 子表导航名
        activeName: 'monthSaleGoalDetails',
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/goal_management/monthSaleGoal/importData"
        },
        dialogUpdateMore: {
          updateName: null,
          dialogFormVisible: false,
          updateData: null,
          optionList: [{
            value: 1,
            label: '销售组织'
          }, {
            value: 2,
            label: '销售区域'
          }, {
            value: 3,
            label: '客户'
          }, {
            value: 4,
            label: '部门'
          }, {
            value: 5,
            label: '制单人'
          }, {
            value: 6,
            label: '科室'
          }, {
            value: 7,
            label: '月份'
          }]
        },
        //打开状态
        openStatus: null,
        //物料来源时间
        dateOptions: [{
          value: '0',
          label: '近一个月'
        }, {
          value: '1',
          label: '近三个月'
        }, {
          value: '2',
          label: '近半年'
        }, {
          value: '3',
          label: '近一年'
        }],
        materialRange: '',
        text: '',
        // 判断操作用户是否属于特殊部门的标志
        isDept: false,
        // 判断操作用户是否属于基卫销售部的标志
        isJiwei: false,
        // 物料分类数组
        classOptions: [],
        // 树形参照
        referCondition: {
          type: '',
          isPage: true,
          title: '',
          index: null
        },
        index: null,
        // 列表标识
        isList: true,
        selection: null,
      };
    },
    created() {
      this.getList();
      this.judge();
    },
    methods: {
      /** 查询月销售/月利润目标填报列表 */
      getList() {
        this.loading = true;
        listMonthSaleGoal(this.queryParams).then(response => {
          this.monthSaleGoalList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.monthSaleGoalList.forEach(item => {
            item.goalSum = item.goalSum.toFixed(2);
          })
        });
      },
      getListDetails() {
        this.loading = true
        getMonthSaleGoalDetails(this.form.id).then(response => {
          this.monthSaleGoalDetailsList = response.data
          this.computeTotal()
          this.form.monthDetailsList = this.monthSaleGoalDetailsList
          updateMonthSaleGoal(this.form).then(response => {})
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.isList = true;
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          code: null,
          goalName: null,
          documentDate: null,
          annual: null,
          customCode: null,
          custom: null,
          saleZoneCode: null,
          saleZone: null,
          creatorCode: null,
          creator: null,
          deptCode: null,
          dept: null,
          goalSum: null,
          notes: null,
          status: null,
          monthDetailsList: null,
          isDept: 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,
          customCode: null,
          custom: null,
          saleZoneCode: null,
          saleZone: null,
          creatorCode: null,
          creator: null,
          deptCode: null,
          dept: null,
          goalSum: null,
          notes: null,
          status: 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
        this.selection = selection
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.isList = false;
        this.openStatus = 'edit';
        this.reset();
        this.monthSaleGoalDetailsList = []
        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() {
        let list = {
          id: null,
          code: null,
          saleOrg: this.$store.state.user.orgName,
          saleZone: this.form.saleZone,
          custom: this.form.custom,
          dept: this.form.dept,
          creator: this.form.creator,
          oneLevelClassifyCode: null,
          oneLevelClassify: null,
          twoLevelClassifyCode: null,
          twoLevelClassify: null,
          materialCode: null,
          specification: null,
          packExplain: null,
          model: null,
          material: null,
          department: null,
          num: null,
          monthly: this.form.documentDate.substring(0, 7),
          goalValue: 0,
          profitTargetValue: 0,
          delFlag: '0',
        }
        this.monthSaleGoalDetailsList.push(list)
        this.computeTotal()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.openStatus = 'edit';
        this.reset();
        const id = row.id || this.ids
        getMonthSaleGoal(id).then(response => {
          this.form = response.data;
          this.form.goalSum = this.form.goalSum.toFixed(2)
          this.monthSaleGoalDetailsList = JSON.parse(JSON.stringify(this.form.monthDetailsList))
          this.open = true;
          this.isList = false;
          this.title = "修改--月销售/月利润目标填报";
        });
      },
      useDoubleClick(row) {
        this.openStatus = 'see';
        this.reset();
        const id = row.id || this.ids
        getMonthSaleGoal(id).then(response => {
          this.form = response.data;
          this.form.goalSum = this.form.goalSum.toFixed(2)
          this.monthSaleGoalDetailsList = JSON.parse(JSON.stringify(this.form.monthDetailsList))
          this.open = true;
          this.isList = false;
          this.title = "查看--月销售/月利润目标填报";
        });
      },
      // 复制按钮
      handleCopy(id) {
        this.openStatus = 'edit';
        this.reset();
        getMonthSaleGoal(id).then(response => {
          this.form = response.data;
          this.form.id = null
          this.form.code = null
          this.form.goalSum = this.form.goalSum.toFixed(2)
          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.monthSaleGoalDetailsList = JSON.parse(JSON.stringify(this.form.monthDetailsList))
          for (const element of this.monthSaleGoalDetailsList) {
            element.id = null
            element.code = null
          }
          this.open = true;
          this.title = "新增--月销售/月利润目标填报";
        })
      },
      /** 提交按钮 */
      submitForm() {
        for (let i = 0; i < this.monthSaleGoalDetailsList.length; i++) {
          this.monthSaleGoalDetailsList[i].saleOrg = this.$store.state.user.orgName;
          this.monthSaleGoalDetailsList[i].saleZone = this.form.saleZone;
          this.monthSaleGoalDetailsList[i].custom = this.form.custom;
          this.monthSaleGoalDetailsList[i].dept = this.form.dept;
          this.monthSaleGoalDetailsList[i].creator = this.form.creator;
        }
        console.log(this.form, 'form');
        if (this.form.saleZone == null || this.form.saleZone == undefined || this.form.saleZone == '' || this.form
          .custom == null || this.form.custom == undefined) {
          return this.$message.error('主表中有必填字段未填！')
        }
        if (this.justiceDetailsList()) {
          return this.$message.error('子表中第' + this.text + '行有必填字段未填，或者目标值为0')
        }
        if (!this.isDept) {
          for (let i = 0; i < this.monthSaleGoalDetailsList.length; i++) {
            for (let j = i + 1; j < this.monthSaleGoalDetailsList.length - i; j++) {
              if (this.monthSaleGoalDetailsList[i].materialCode == this.monthSaleGoalDetailsList[j].materialCode) {
                return this.$message.error('子表存在重复物料');
              }
            }
          }
        }
        this.$refs["form"].validate(valid => {
          if (this.isJiwei == true) {
            this.form.isDept = '2';
          } else if (this.isDept == true && this.isJiwei == false) {
            this.form.isDept = '1';
          }
          if (valid) {
            if (this.form.id != null) {
              this.form.monthDetailsList = JSON.parse(JSON.stringify(this.monthSaleGoalDetailsList))
              let ids = this.delMonthSaleGoalDetailsList.map((item) => {
                return item.id;
              })
              ids = ids.filter((item) => {
                return item != null;
              })
              console.log(ids, 'ids')
              this.$modal.loading("保存中...");
              updateMonthSaleGoal(this.form).then(response => {
                if (ids != null && ids.length != 0) {
                  delMonthSaleGoalDetails(ids);
                }
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.isList = true;
                this.getList();
              }).finally(e => {
                this.$modal.closeLoading();
              });
            } else {
              this.form.status = '0'
              this.form.monthDetailsList = JSON.parse(JSON.stringify(this.monthSaleGoalDetailsList))
              console.log(this.form);
              this.$modal.loading("保存中...");
              addMonthSaleGoal(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.isList = true;
                this.getList();
              }).finally(e => {
                this.$modal.closeLoading();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除月销售/月利润目标填报单据编号为"' + row.code + '"的数据项？').then(function () {
          return delMonthSaleGoal(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      // 详情页明细行删除
      handleDeleteDetails(row) {
        this.$confirm('是否确认删除？').then(_ => {
          row.delFlag = '2';
          this.delMonthSaleGoalDetailsList.push(row);
          this.monthSaleGoalDetailsList = this.monthSaleGoalDetailsList.filter((item) => {
            return item.delFlag == '0';
          })
        }).catch(_ => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('goal_management/monthSaleGoal/export', {
          ...this.queryParams
        }, `monthSaleGoal_${new Date().getTime()}.xlsx`)
      },
      handleExportDetails() {
        this.download('goal_management/monthSaleGoalDetails/export', {
          ...this.queryParams
        }, `monthSaleGoalDetails_${new Date().getTime()}.xlsx`)
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      // 复制明细
      handleCopyDetails(row) {
        let list = {
          id: null,
          code: row.code,
          saleOrg: row.saleOrg,
          saleZone: row.saleZone,
          custom: row.custom,
          dept: row.dept,
          creator: row.creator,
          oneLevelClassifyCode: row.oneLevelClassifyCode,
          oneLevelClassify: row.oneLevelClassify,
          twoLevelClassifyCode: row.twoLevelClassifyCode,
          twoLevelClassify: row.twoLevelClassify,
          materialCode: row.materialCode,
          material: row.material,
          department: row.department,
          num: row.num,
          monthly: row.monthly,
          goalValue: row.goalValue,
          profitTargetValue: row.profitTargetValue
        }
        this.monthSaleGoalDetailsList.push(list)
        this.computeTotal()
      },
      // 计算主表合计
      computeTotal() {
        let list = this.monthSaleGoalDetailsList
        let sum = 0
        for (const listElement of list) {
          sum = (sum * 1000000 + listElement.goalValue * 1000000) / 1000000
        }
        this.form.goalSum = sum.toFixed(2)
      },
      getSummaries(param) {
        return getSummary(param)
      },
      // 子表table加必填标志
      addRedStar(h, {
        column
      }) {
        return [
          h('span', {
            style: 'color: #F56C6C'
          }, '*'),
          h('span', '' + column.label)
        ]
      },
      // 子表table通过判断条件加必填标志
      addRedStarChange(h, {
        column
      }) {
        if (this.isDept) {
          return [
            h('span', '' + column.label)
          ]
        } else {
          return [
            h('span', {
              style: 'color: #F56C6C'
            }, '*'),
            h('span', '' + column.label)
          ]
        }
      },
      justiceDetailsList() {
        this.text = ' ';
        let isFlag = [];
        let count = 1;
        const arr = JSON.parse(JSON.stringify(this.monthSaleGoalDetailsList))
        if (this.isDept) {
          for (const element of arr) {
            const flag1 = (element.saleOrg !== null) && (element.saleZone !== null) && (element.custom !== null) && (
              element.dept !== null) && (element.creator !== null) && (element.oneLevelClassify !== null) && (element
              .oneLevelClassifyCode !== null) && (element.monthly !== null) && (element.goalValue !== 0);
            const flag2 = (element.saleOrg !== undefined) && (element.saleZone !== undefined) && (element.custom !==
              undefined) && (element.dept !== undefined) && (element.creator !== undefined) && (element
              .oneLevelClassify !==
              undefined) && (element.oneLevelClassifyCode !== undefined) && (element.monthly !== undefined);
            if (flag1 && flag2) {
              isFlag.push(true);
            } else {
              this.text += '[' + count + '] ';
              isFlag.push(false);
            }
            count++;
          }
          for (const flag of isFlag) {
            if (!flag) {
              return true;
            }
          }
        } else {
          for (const element of arr) {
            const flag1 = (element.saleOrg !== null) && (element.saleZone !== null) && (element.custom !== null) && (
              element.dept !== null) && (element.creator !== null) && (element.materialCode !== null) && (element
              .material !== null) && (element.monthly !== null) && (element.goalValue !== 0);
            const flag2 = (element.saleOrg !== undefined) && (element.saleZone !== undefined) && (element.custom !==
              undefined) && (element.dept !== undefined) && (element.creator !== undefined) && (element
              .materialCode !==
              undefined) && (element.material !== undefined) && (element.monthly !== undefined);
            if (flag1 && flag2) {
              isFlag.push(true);
            } else {
              this.text += '[' + count + '] ';
              isFlag.push(false);
            }
            count++;
          }
          for (const flag of isFlag) {
            if (!flag) {
              return true;
            }
          }
        }
      },
      setBeginAndEnd() {
        let array = this.documentDateRange
        if (this.documentDateRange !== 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()
        }
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.open = true;
        if (this.open) {
          this.upload.title = "月销售/月利润目标填报明细导入"
          this.upload.url = process.env.VUE_APP_BASE_API + "goal_management/monthSaleGoalDetails/importData/" + this
            .form.id
        } else {
          this.upload.title = "月销售/月利润目标填报导入";
          this.upload.url = process.env.VUE_APP_BASE_API + "goal_management/monthSaleGoal/importData"
        }
      },
      /** 下载模板操作 */
      importTemplate() {
        if (this.open) {
          this.download('goal_management/monthSaleGoalDetails/importTemplate', {},
            `monthSaleGoalDetails_${new Date().getTime()}.xlsx`)
        } else {
          this.download('goal_management/monthSaleGoal/importTemplate', {},
            `monthSaleGoal_${new Date().getTime()}.xlsx`)
        }
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        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
          });
        if (this.open) {
          let array = response.data
          for (const arrayElement of array) {
            arrayElement.id = null
            this.monthSaleGoalDetailsList.push(arrayElement)
          }
          this.computeTotal()
        } else {
          this.getList();
        }
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      // 选择物料后，给一级分类和二级分类复赋值
      setClassify(one, two, obj, row) {
        const oneArray = one.split("&")
        const twoArray = two.split("&")
        // 物料提醒文本
        const memo = '名称：' + row.material + '； 编码：' + row.materialCode + '； 规格：' + row.specification + '；  包装：' + row
          .packExplain + '； 型号：' + row.model + '。';
        obj.memo = memo;
        obj.oneLevelClassifyCode = oneArray[1]
        obj.oneLevelClassify = oneArray[0]
        obj.twoLevelClassifyCode = twoArray[1]
        obj.twoLevelClassify = twoArray[0]
      },
      // 批量修改对话框的方法
      dialogUpdateMoreSave() {
        console.log(this.dialogUpdateMore);
        if (this.dialogUpdateMore.updateData === null) {
          return this.$message.error('请输入修改值')
        }
        const array = JSON.parse(JSON.stringify(this.monthSaleGoalDetailsList))
        if (array.length !== 0) {
          let condition = this.dialogUpdateMore.updateName
          for (const element of array) {
            if (condition === 1) {
              element.saleOrg = JSON.parse(JSON.stringify(this.dialogUpdateMore.updateData))
            } else if (condition === 2) {
              element.saleZone = JSON.parse(JSON.stringify(this.dialogUpdateMore.updateData))
            } else if (condition === 3) {
              element.custom = JSON.parse(JSON.stringify(this.dialogUpdateMore.updateData))
            } else if (condition === 4) {
              element.dept = JSON.parse(JSON.stringify(this.dialogUpdateMore.updateData))
            } else if (condition === 5) {
              element.creator = JSON.parse(JSON.stringify(this.dialogUpdateMore.updateData))
            } else if (condition === 6) {
              element.department = JSON.parse(JSON.stringify(this.dialogUpdateMore.updateData))
            } else if (condition === 7) {
              element.monthly = JSON.parse(JSON.stringify(this.dialogUpdateMore.updateData))
            }
          }
        }
        this.monthSaleGoalDetailsList = array
        this.dialogUpdateMore.dialogFormVisible = !this.dialogUpdateMore.dialogFormVisible
        this.dialogUpdateMore.updateData = null
        this.dialogUpdateMore.updateName = null
      },
      changeDialogData() {
        this.dialogUpdateMore.updateData = null
      },
      resetDialogUpdateMore() {
        this.dialogUpdateMore.updateName = null
        this.dialogUpdateMore.updateData = null
      },
      //提交
      handleSubmit(row) {
        this.$modal.loading("提交中...");
        submit(row.id).then(res => {
          if (res.code === 200) {
            this.$modal.notifySuccess("提交成功");
            this.$modal.closeLoading();
            row.status = '1';
          }
        }).catch(err => {
          this.$message.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: "3"
        }
        rollBack(params).then(res => {
          if (res.code === 200) {
            this.$modal.notifySuccess("收回成功");
            this.$modal.closeLoading();
            row.status = '0';
          }
        }).catch(err => {
          this.$message.error(err);
          this.$modal.closeLoading();
        })
      },
      //模板下载
      handleTemplateDownload() {
        this.download('/goal_management/monthSaleGoalDetails/importTemplate', {},
          `月销售/月利润目标填报明细导入模板_${new Date().getTime()}.xlsx`)
      },
      //导入
      handleImport(file) {
        this.loading = true;
        let formData = new FormData()
        formData.append('file', file.file)
        importData(formData).then((res) => {
          console.log('res', res);
          if (res.code == '200') {
            this.monthSaleGoalDetailsList.push.apply(this.monthSaleGoalDetailsList, res.data);
            this.$message.success(res.msg);
          } else {
            this.$message.success(res.msg);
          }
          this.loading = false;
        }).catch((e) => {
          this.$message.error(e.message)
        }).finally((e) => {
          this.$refs['upload'].clearFiles();
          this.loading = false;
        })
      },
      //查询该时间范围内对应客户的物料数据
      getMaterialList() {
        this.loading = true;
        let params = [];
        params[0] = this.form.customCode;
        params[1] = this.materialRange;
        if (this.isDept && !this.isJiwei) {
          params[2] = 'HUNAN';
        } else {
          params[2] = 'JIWEI_OR_PUTONG'
        }
        console.log(params, 'params')
        getMaterialRangeList(params).then((res) => {
          console.log(res, 'res')
          this.monthSaleGoalDetailsList = res;
          for (const item of this.monthSaleGoalDetailsList) {
            item.saleOrg = this.$store.state.user.orgName;
            item.saleZone = this.form.saleZone;
            item.custom = this.form.custom;
            item.dept = this.form.dept;
            item.creator = this.form.creator;
            item.monthly = this.form.documentDate.substring(0, 7);
          }
        }).catch((e) => {
          this.$message.error(e.message)
        }).finally((e) => {
          this.loading = false;
        })
      },
      calculate(row) {
        if (!(row.price == 0 || row.price == null || row.price == undefined)) {
          row.goalValue = row.num * row.price;
        }
      },
      // 判断操作人部门是否属于湖南公司、湖南公司本部、基卫销售部
      judge() {
        let that = this;
        that.isDept = false;
        that.isJiwei = false;
        let data = '湖南公司';
        getDeptIds(data).then(hunan => {
          for (const h of hunan) {
            if (that.$store.state.user.deptId === h) {
              that.isDept = true;
            }
          }
        })
        data = '基卫销售部';
        getDeptIds(data).then(jiwei => {
          for (const j of jiwei) {
            if (that.$store.state.user.deptId === j) {
              that.isDept = true;
              that.isJiwei = true;
            }
          }
        })
      },
      // 树形参照
      chooseTreeReferForMain(type, isPage, title, index) {
        this.referCondition.type = type;
        this.referCondition.isPage = isPage;
        this.referCondition.title = title;
        this.index = null;
        this.index = index;
        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.monthSaleGoalDetailsList[this.index].oneLevelClassifyCode = selection[0].code;
          this.monthSaleGoalDetailsList[this.index].oneLevelClassify = selection[0].name;
        } else if (this.referCondition.title === '二级物料分类') {
          if (this.classOptions[0].code.lastIndexOf("-") == 3 || this.classOptions[0].code.indexOf("90") == 0) {
            this.monthSaleGoalDetailsList[this.index].oneLevelClassifyCode = selection[0].parentCode;
            this.monthSaleGoalDetailsList[this.index].oneLevelClassify = selection[0].parentName;
            this.monthSaleGoalDetailsList[this.index].twoLevelClassifyCode = selection[0].code;
            this.monthSaleGoalDetailsList[this.index].twoLevelClassify = selection[0].name;
          } else {
            return this.$message.info('请在二级分类下选择');
          }
        }
      },
      // 当单据日期改变时改变明细月份
      setItemMonthly() {
        for (let i = 0; i < this.monthSaleGoalDetailsList.length; i++) {
          this.monthSaleGoalDetailsList[i].monthly = this.form.documentDate.substring(0, 7);
        }
      },
      // 详情页批量删除
      batchRemove() {
        if (this.selection == null || this.selection == undefined || this.selection.length == 0) {
          this.$modal.notifyWarning("请至少选择一条明细！");
        } else {
          this.$confirm('是否确认批量删除？').then(_ => {
            this.selection.forEach((item) => {
              item.delFlag = "2";
            });
            let delList = [];
            delList = this.monthSaleGoalDetailsList.filter((item) => {
              return item.delFlag == "2";
            });
            this.monthSaleGoalDetailsList =
              this.monthSaleGoalDetailsList.filter((item) => {
                return item.delFlag == "0";
              });
            this.delMonthSaleGoalDetailsList.push(...delList);
          }).catch(_ => {});
        }
      },
    }
  }

</script>
