<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="目标名称" prop="goalName">
        <el-input
          v-model="queryParams.goalName"
          placeholder="请输入年度销售目标名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据日期" prop="documentDate">
        <el-date-picker
          v-model="queryParams.documentDateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          clearable
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          placeholder="请选择单据日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <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-form-item>
      <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-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-form-item label="销售区域" prop="saleZone">
        <el-popover-select-v2 v-model="queryParams.saleZone" title="销售区域" valueKey="name"
                              referName="CUSTOMER_PARAM"
                              :dataMapping="{ saleZoneCode: 'code', saleZone: 'name'}"
                              :source.sync="queryParams" placeholder="请输入销售区域" @keyup.enter.native="handleQuery">
        </el-popover-select-v2>
      </el-form-item>
      <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-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-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goal_management:annualSaleGoal:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goal_management:annualSaleGoal:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-grape"
          size="mini"
          :disabled="multiple"
          v-hasPermi="['goal_management:annualSaleGoal:submit']"
        >提交
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handleCommand">
          <el-button type="primary" size="mini" plain icon="el-icon-upload">
            导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="importModel">导入模板</el-dropdown-item>
            <el-dropdown-item command="import">导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </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>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </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-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goal_management:annualSaleGoal:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goal_management:annualSaleGoal:remove']"
          >删除
          </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="CUSTOMER_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-col :span="6">
            <el-form-item label="操作">
              <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
              <el-button @click="cancel" size="medium">返 回</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div id="addDetails">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddDetails">增行</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="annualSaleGoalDetailsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" fixed />
          <el-table-column label="销售组织" align="center" prop="saleOrg" width="180" :render-header="addRedStar">
            <template slot-scope="scope">
              <el-popover-select-v2 v-model="annualSaleGoalDetailsList[scope.$index].saleOrg" title="销售组织" valueKey="name"
                                    referName="CUSTOMER_PARAM"
                                    @blur="validateField(scope.row, 'saleOrg')"
                                    :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" prop="saleZone" width="180" :render-header="addRedStar">
            <template slot-scope="scope">
              <el-popover-select-v2 v-model="annualSaleGoalDetailsList[scope.$index].saleZone" title="销售区域" valueKey="name"
                                    referName="CUSTOMER_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" prop="custom" width="180" :render-header="addRedStar">
            <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" prop="creator" width="180" :render-header="addRedStar">
            <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" prop="oneLevelClassify" width="220" :render-header="addRedStar">
            <template slot-scope="scope">
              <el-select v-model="annualSaleGoalDetailsList[scope.$index].oneLevelClassify" size="mini" clearable
                         @focus="chooseTreeReferForDetails('MATERIALCLASSIFY_PARAM', false, '一级物料分类', scope.$index)"
                         style="width: 200px">
                <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="二级分类" align="center" prop="twoLevelClassify" width="220">
            <template slot-scope="scope">
              <el-select v-model="annualSaleGoalDetailsList[scope.$index].twoLevelClassify" size="mini" clearable
                         @focus="chooseTreeReferForDetails('MATERIALCLASSIFY_PARAM', false, '二级物料分类', scope.$index)"
                         style="width: 200px">
                <el-option v-for="item in classOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料" align="center" prop="material" width="180">
            <template slot-scope="scope">
              <el-popover-select-v2 v-model="annualSaleGoalDetailsList[scope.$index].material" title="物料" valueKey="name"
                                    referName="MATERIAL_PARAM"
                                    :dataMapping="{ materialCode: 'code', material: 'name'}"
                                    :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>
      </div>
    </el-drawer>

    <TreeRefers ref="treeDetails" @doSubmit="selectionsToInputForDetails" :single="true"/>
  </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 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: true,
      // 总条数
      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'}]
      },
      // 参照条件
      referCondition: {type: '', isPage: true, title: '', index: null},
      classOptions: [],
      // 子表数组
      annualSaleGoalDetailsList: []
    };
  },
  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);
        for (const element of this.annualSaleGoalList) {
          if (element.documentStatus === '0') {
            element.documentStatus = '未提交'
          } else if (element.documentStatus === '1') {
            element.documentStatus = '审核中'
          } else {
            element.documentStatus = '已审核'
          }
        }
      });
    },
    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;
    },
    handleAddDetails() {
      let list = {
        id: null,
        code: null,
        saleOrg: this.form.saleZone,
        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,
        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.annualSaleGoalDetailsList = this.form.annualGoalMergeDetails
        this.open = true;
        this.title = "修改年度销售目标";
        if (this.form.documentStatus === '0') {
          this.form.documentStatus = '未提交'
        } else if (this.form.documentStatus === '1') {
          this.form.documentStatus = '审批中'
        } else if (this.form.documentStatus === '2') {
          this.form.documentStatus = '已审核'
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.justiceDetailsList()) {
        return this.$message.error('子表有必填字段没有赋值')
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.documentStatus === '未提交') {
              this.form.documentStatus = 0
            } else if (this.form.documentStatus === '审批中') {
              this.form.documentStatus = 1
            } else {
              this.form.documentStatus = 2
            }
            this.form.annualGoalMergeDetails = this.annualSaleGoalDetailsList
            updateAnnualSaleGoal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.annualGoalMergeDetails = this.annualSaleGoalDetailsList
            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
      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
    },
    // 树形物料分类
    chooseTreeReferForDetails(type, isPage, title, index) {
      this.referCondition.type = type
      this.referCondition.isPage = isPage
      this.referCondition.title = title
      this.referCondition.index = index
      this.$refs.treeDetails.init(this.referCondition)
    },
    selectionsToInputForDetails(selection) {
      this.classOptions.push(selection)
      if (this.referCondition.title === '一级物料分类') {
        if (selection.code.length !== 1) {
          return this.$message.info('请在一级分类中选择')
        }
        if (selection.code !== this.annualSaleGoalDetailsList[this.referCondition.index].oneLevelClassifyCode) {
          this.annualSaleGoalDetailsList[this.referCondition.index].twoLevelClassifyCode = null
          this.annualSaleGoalDetailsList[this.referCondition.index].twoLevelClassify = null
        }
        this.annualSaleGoalDetailsList[this.referCondition.index].oneLevelClassifyCode = selection.code
        this.annualSaleGoalDetailsList[this.referCondition.index].oneLevelClassify = selection.name
      } else if (this.referCondition.title === '二级物料分类') {
        if (selection.code.length !== 4) {
          return this.$message.info('请在二级分类中选择')
        } else if (selection.code[0] !== this.annualSaleGoalDetailsList[this.referCondition.index].oneLevelClassifyCode) {
          return this.$message.error('所选择的二级物料分类不属于一级分类')
        }
        this.annualSaleGoalDetailsList[this.referCondition.index].twoLevelClassifyCode = selection.code
        this.annualSaleGoalDetailsList[this.referCondition.index].twoLevelClassify = selection.name
      }
    },
    // 给table添加必填项
    addRedStar(h, { column }) {
      return [
        h('span', { style: 'color: #F56C6C' }, '*'),
        h('span', '' + column.label)
      ]
    },
    // 判断子表的字段是否都填了
    justiceDetailsList() {
      const arr = JSON.parse(JSON.stringify(this.annualSaleGoalDetailsList))
      for (const element of arr) {
        if (element.saleOrg === null || element.saleZone === null || element.custom === null || element.creator === null || element.oneLevelClassify === null) {
          return false
        }
      }
      return true
    },
    handleCommand(command) {
      // 执行对应的功能
      if (command === 'importModel') {
        // 执行选项1的功能
        console.log('导入模板');
      } else if (command === 'import') {
        // 执行选项2的功能
        console.log('导入');
      } else if (command === 'export') {
        console.log('导出主表');
        this.handleExport()
      } else if (command === 'exportDetails') {
        console.log('导出明细');
        this.handleExportDetails()
      }
    }
  }
};
</script>
