<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <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="queryParams.documentDateRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              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="small" :inline="true" v-show="showSearch" label-width="68px">
      <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">
            <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: 'code', 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="documentStatus">
            <el-select v-model="queryParams.documentStatus" 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-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-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-grape"
          size="mini"
          :disabled="multiple"
        >提交
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</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="annualSaleGoalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
      <el-table-column label="编码" align="center" prop="code" width="180"/>
      <el-table-column label="目标名称" align="center" prop="goalName" width="180"/>
      <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"/>
      <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"/>
      <el-table-column label="部门" align="center" prop="dept" width="180"/>
      <el-table-column label="目标合计" align="center" prop="goalTotal"/>
      <el-table-column label="备注" align="center" prop="notes" width="180"/>
      <el-table-column label="单据状态" align="center" prop="documentStatus"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleCopy(scope.row.id)"
          >复制
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(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"
      @pagination="getList"
    />

    <el-drawer :title="title" :visible.sync="open" direction="rtl" :before-close="handleClose" size="100%">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="编码后端自动生成" clearable disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="目标名称" prop="goalName">
              <el-input v-model="form.goalName" placeholder="目标名称后端自动生成" clearable 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" format="yyyy-MM-dd"
                              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" 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">
              <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="goalTotal">
              <el-input v-model="form.goalTotal" placeholder="目标合计自动计算" clearable disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="notes">
              <el-input v-model="form.notes" placeholder="请输入备注" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据状态" prop="documentStatus">
              <el-input v-model="form.documentStatus" placeholder="未提交" clearable disabled/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div id="addDetails">
        <el-row :gutter="10" class="mb8" style="margin-left: 80%">
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入明细</el-button>
          </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-row>
        <el-tabs v-model="activeName">
          <el-tab-pane label="年销售目标填报明细" name="annualSaleGoalDetails">
            <el-table max-height="300" show-summary :summary-method="getSummaries" v-loading="loading" :data="annualSaleGoalDetailsList" @selection-change="handleSelectionChange">
              <el-table-column label="序号" type="index" width="70" align="center" fixed />
              <el-table-column label="销售组织" align="center" width="180" :render-header="(h, obj) => addRedStar(h, obj, '0')">
                <template slot-scope="scope">
                  <el-popover-select-v2 v-model="annualSaleGoalDetailsList[scope.$index].saleOrg" title="销售组织" valueKey="name"
                                        referName="ORG_PARAM"
                                        :dataMapping="{ saleOrgCode: 'code', saleOrg: 'name'}"
                                        :source.sync="annualSaleGoalDetailsList[scope.$index]" placeholder="请输入销售组织">
                  </el-popover-select-v2>
                </template>
              </el-table-column>
              <el-table-column label="销售区域" align="center" width="180" :render-header="(h, obj) => addRedStar(h, obj, '0')">
                <template slot-scope="scope">
                  <el-popover-select-v2 v-model="annualSaleGoalDetailsList[scope.$index].saleZone" title="销售区域" valueKey="name"
                                        referName="MK_SALESAREA_PARAM"
                                        :dataMapping="{ saleZoneCode: 'code', saleZone: 'name'}"
                                        :source.sync="annualSaleGoalDetailsList[scope.$index]" placeholder="请输入销售区域">
                  </el-popover-select-v2>
                </template>
              </el-table-column>
              <el-table-column label="客户" align="center" width="180" :render-header="(h, obj) => addRedStar(h, obj, '0')">
                <template slot-scope="scope">
                  <el-popover-select-v2 v-model="annualSaleGoalDetailsList[scope.$index].custom" title="客户" valueKey="name"
                                        referName="CUSTOMER_PARAM"
                                        :dataMapping="{ customCode: 'code', custom: 'name'}"
                                        :source.sync="annualSaleGoalDetailsList[scope.$index]" placeholder="请输入客户">
                  </el-popover-select-v2>
                </template>
              </el-table-column>
              <el-table-column label="负责人" align="center" width="180" :render-header="(h, obj) => addRedStar(h, obj, '0')">
                <template slot-scope="scope">
                  <el-popover-select-v2 v-model="annualSaleGoalDetailsList[scope.$index].creator" title="负责人" valueKey="name"
                                        referName="CONTACTS_PARAM"
                                        :dataMapping="{ creatorCode: 'code', creator: 'name'}"
                                        :source.sync="annualSaleGoalDetailsList[scope.$index]" placeholder="请输入负责人">
                  </el-popover-select-v2>
                </template>
              </el-table-column>
              <el-table-column label="一级分类" align="center" width="180" :render-header="(h, obj) => addRedStar(h, obj, '0')">
                <template slot-scope="scope">
                  <el-input v-model="annualSaleGoalDetailsList[scope.$index].oneLevelClassify" placeholder="请输入一级分类" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="二级分类" align="center" width="180" :render-header="(h, obj) => addRedStar(h, obj, '0')">
                <template slot-scope="scope">
                  <el-input v-model="annualSaleGoalDetailsList[scope.$index].twoLevelClassify" placeholder="请输入二级分类" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="物料" align="center" width="220" :render-header="(h, obj) => addRedStar(h, obj, '0')">
                <template slot-scope="scope">
                  <el-popover-select-v2 v-model="annualSaleGoalDetailsList[scope.$index].material" title="物料" valueKey="name"
                                        referName="MATERIAL_PARAM"
                                        @change="setClassify(scope.row.oneLevelClassify, scope.row.twoLevelClassify, annualSaleGoalDetailsList[scope.$index])"
                                        :dataMapping="{ materialCode: 'code', material: 'name', oneLevelClassify: 'oneClass', twoLevelClassify: 'twoClass'}"
                                        :source.sync="annualSaleGoalDetailsList[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="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[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, annualSaleGoalDetailsList[scope.$index])" v-model="annualSaleGoalDetailsList[scope.$index].decemberGoal" :precision="2" :step="0.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.$index, 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">返 回</el-button>
        </div>
      </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="CONTACTS_PARAM"
                                :dataMapping="{updateData: 'name'}"
                                :source.sync="dialogUpdateMore" placeholder="请输入制单人">
          </el-popover-select-v2>
          <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>
  </div>
</template>

<script>
import {
  listAnnualSaleGoal,
  getAnnualSaleGoal,
  delAnnualSaleGoal,
  addAnnualSaleGoal,
  updateAnnualSaleGoal
} from "@/api/business/spd/goal_management/annualSaleGoal";
import {
  delAnnualSaleGoalDetails,
  getAnnualSaleGoalDetails
} from "@/api/business/spd/goal_management/annualSaleGoalDetails"
import { getToken } from "@/utils/auth";
import { getSummary } from "@/api/business/spd/goal_management/commonWays";

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

export default {
  name: "AnnualSaleGoal",
  components: {
    TreeRefers, ElPopoverSelectV2
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 年度销售目标表格数据
      annualSaleGoalList: [],
      // 弹出层标题
      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,
        goalTotal: null,
        notes: null,
        documentStatus: null,
        delFlag: 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,
        goalTotal: null,
        notes: null,
        documentStatus: '开立态',
        deleteStatus: 0,
        annualGoalMergeDetails: []
      },
      formDetails: {
        id: null,
        code: null,
        saleOrg: null,
        saleZone: null,
        custom: null,
        creator: null,
        oneLevelClassifyCode: null,
        oneLevelClassify: null,
        twoLevelClassifyCode: null,
        twoLevelClassify: null,
        materialCode: null,
        material: null,
        totalGoal: 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
      },
      // 表单校验
      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'}]
      },
      // 子表数组
      annualSaleGoalDetailsList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/goal_management/annualSaleGoal/importData"
      },
      activeName: 'annualSaleGoalDetails',
      dialogUpdateMore: {
        updateName: null,
        dialogFormVisible: false,
        updateData: null,
        optionList:[{value: 1, label: '销售组织'}, {value: 2, label: '销售区域'}, {value: 3, label: '客户'}, {value: 4, label: '制单人'},]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询年度销售目标列表 */
    getList() {
      this.loading = true;
      listAnnualSaleGoal(this.queryParams).then(response => {
        this.annualSaleGoalList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.annualSaleGoalList);
      });
    },
    getListDetails() {
      this.loading = true
      getAnnualSaleGoalDetails(this.form.id).then(response => {
        this.annualSaleGoalDetailsList = response.data
        this.computeTotal()
        this.form.annualGoalMergeDetails = this.annualSaleGoalDetailsList
        updateAnnualSaleGoal(this.form).then(response => {})
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      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,
        goalTotal: null,
        notes: null,
        documentStatus: null,
        deleteStatus: 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,
        goalTotal: null,
        notes: null,
        documentStatus: null,
        delFlag: null,
        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.reset();
      this.title = "添加--年度销售目标";
      this.annualSaleGoalDetailsList = []
      this.open = true;
      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.creator = this.$store.state.user.nickName
      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,
        creator: this.form.creator,
        oneLevelClassifyCode: null,
        oneLevelClassify: null,
        twoLevelClassifyCode: null,
        twoLevelClassify: null,
        materialCode: null,
        material: null,
        totalGoal: '0.00',
        januaryGoal: null,
        februaryGoal: null,
        marchGoal: null,
        aprilGoal: null,
        mayGoal: null,
        juneGoal: null,
        julyGoal: null,
        augustGoal: null,
        septemberGoal: null,
        octoberGoal: null,
        novemberGoal: null,
        decemberGoal: null
      }
      this.annualSaleGoalDetailsList.push(list)
      this.computeTotal()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAnnualSaleGoal(id).then(response => {
        this.form = response.data;
        this.saveFormTwoPoint(this.form)
        this.annualSaleGoalDetailsList = this.form.annualGoalMergeDetails
        this.open = true;
        this.title = "修改--年度销售目标";
      });
    },
    // 复制按钮
    handleCopy(id) {
      this.reset();
      getAnnualSaleGoal(id).then(response => {
        console.log(response);
        this.form = response.data;
        this.form.id = null
        this.form.code = null
        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.saveFormTwoPoint(this.form)
        this.annualSaleGoalDetailsList = JSON.parse(JSON.stringify(this.form.annualGoalMergeDetails))
        for (const element of this.annualSaleGoalDetailsList) {
          element.id = null
          element.code = null
        }
        this.open = true;
        this.title = "新增--年度销售目标";
        console.log(this.form);
      })
    },
    // 进入修改复制界面保留两位小数
    saveFormTwoPoint(form) {
      form.goalTotal = form.goalTotal.toFixed(2)
      for (const element of form.annualGoalMergeDetails) {
        element.totalGoal = element.totalGoal.toFixed(2)
      }
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.justiceDetailsList()) {
        return this.$message.error('子表有必填字段没有赋值')
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.annualGoalMergeDetails = JSON.parse(JSON.stringify(this.annualSaleGoalDetailsList))
            updateAnnualSaleGoal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.documentStatus = '未提交'
            this.form.annualGoalMergeDetails = JSON.parse(JSON.stringify(this.annualSaleGoalDetailsList))
            console.log(this.form);
            addAnnualSaleGoal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除年度销售目标编号为"' + ids + '"的数据项？').then(function () {
        return delAnnualSaleGoal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleDeleteDetails(index, row) {
      if (this.form.id === null) {
        this.annualSaleGoalDetailsList.splice(index, 1)
        this.computeTotal()
      } else {
        if (row.id !== null) {
          this.$modal.confirm('是否确认删除年度销售目标明细编号为"' + row.id + '"的数据项？').then(function () {
            return delAnnualSaleGoalDetails(row.id)
          }).then(() => {
            this.getListDetails()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        } else {
          this.annualSaleGoalDetailsList.splice(index, 1)
          this.$message.success('删除成功')
          this.computeTotal()
        }
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('goal_management/annualSaleGoal/export', {
        ...this.queryParams
      }, `annualSaleGoal_${new Date().getTime()}.xlsx`)
    },
    handleExportDetails() {
      this.download('goal_management/annualSaleGoalDetails/export', {
        ...this.queryParams
      }, `annualSaleGoalMerge_${new Date().getTime()}.xlsx`)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
          this.reset()
        })
        .catch(_ => {
        });
    },
    // 复制明细
    handleCopyDetails(row) {
      let list = {
        id: null,
        code: row.code,
        saleOrg: row.saleOrg,
        saleZone: row.saleZone,
        custom: row.custom,
        creator: row.creator,
        oneLevelClassifyCode: row.oneLevelClassifyCode,
        oneLevelClassify: row.oneLevelClassify,
        twoLevelClassifyCode: row.oneLevelClassifyCode,
        twoLevelClassify: row.twoLevelClassify,
        materialCode: row.materialCode,
        material: row.material,
        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
      }
      this.annualSaleGoalDetailsList.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.annualSaleGoalDetailsList[index].totalGoal = sum.toFixed(2)
      this.computeTotal()
    },
    // 计算主表合计
    computeTotal() {
      let list = this.annualSaleGoalDetailsList
      let sum = 0
      for (const listElement of list) {
        sum = (sum * 1000000 + listElement.totalGoal * 1000000) / 1000000
      }
      this.form.goalTotal = sum.toFixed(2)
    },
    getSummaries(param) {
      return getSummary(param)
    },
    // 给table添加必填项
    addRedStar(h, { column }, required) {
      if (required === '0') {
        return [
          h('span', { style: 'color: #F56C6C' }, '*'),
          h('span', '' + column.label)
        ]
      } else {
        return [
          // h('span', { style: 'color: #F56C6C' }, '*'),
          h('span', '' + column.label)
        ]
      }
    },
    // 判断子表的字段是否都填了
    justiceDetailsList() {
      const arr = JSON.parse(JSON.stringify(this.annualSaleGoalDetailsList))
      for (const element of arr) {
        const flag1 = (element.saleZone !== null) && (element.saleOrg !== null) && (element.custom !== null) && (element.creator !== null) && (element.materialCode !== null) && (element.material !== null)
        const flag2 = (element.saleOrg !== undefined) && (element.saleZone !== undefined) && (element.custom !== undefined) && (element.creator !== undefined) && (element.materialCode != undefined) && (element.material !== undefined)
        if (flag1 && flag2) {
          return true
        }
      }
      return false
    },
    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/annualSaleGoalDetails/importData/" + this.form.id
      } else {
        this.upload.title = "年销售目标填报导入";
        this.upload.url = process.env.VUE_APP_BASE_API + "goal_management/annualSaleGoal/importData"
      }
    },
    /** 下载模板操作 */
    importTemplate() {
      if (this.open) {
        this.download('goal_management/annualSaleGoalDetails/importTemplate', {
        }, `annualSaleGoalDetails_${new Date().getTime()}.xlsx`)
      } else {
        this.download('goal_management/annualSaleGoal/importTemplate', {
        }, `annualSaleGoal_${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 });
      if (this.open) {
        const array = response.data
        for (const arrayElement of array) {
          arrayElement.id = null
          this.annualSaleGoalDetailsList.push(arrayElement)
        }
        this.computeTotal()
      } else {
        this.getList();
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 选择物料后，给一级分类和二级分类复赋值
    setClassify(one, two, obj) {
      const oneArray = one.split("&")
      const twoArray = two.split("&")
      obj.oneLevelClassifyCode = oneArray[1]
      obj.oneLevelClassify = oneArray[0]
      obj.twoLevelClassifyCode = twoArray[1]
      obj.twoLevelClassify = twoArray[0]
      console.log(obj);
    },
    // 批量修改对话框的方法
    dialogUpdateMoreSave() {
      console.log(this.dialogUpdateMore);
      if (this.dialogUpdateMore.updateData === null) {
        return this.$message.error('请输入修改值')
      }
      const array = JSON.parse(JSON.stringify(this.annualSaleGoalDetailsList))
      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.creator = JSON.parse(JSON.stringify(this.dialogUpdateMore.updateData))
          }
        }
      }
      this.annualSaleGoalDetailsList = 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
    }
  }
};
</script>
