<!-- 年销售目标合并-详情 -->
<script>
import useColumns from "./columns";
import { mergeAnnualSaleMergeDetails } from "@/api/business/spd/goal_management/annualSaleMergeDetails";
import {
  addAnnualSaleGoalMerge,
  getAnnualSaleGoalMerge,
  updateAnnualSaleGoalMerge,
} from "@/api/business/spd/goal_management/annualSaleGoalMerge";
export default {
  name: "AnnualSaleGoalMergeDetails",
  props: {
    dict: {
      type: Object,
    },
    addType: {
      type: String,
      default: "add",
    },
    data: {
      type: Object,
    },
  },
  components: {
    ElSuperForm: () => import("@/components/super-form/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
    ElPopoverTreeSelect: () =>
      import("@/components/popover-tree-select/index.vue"),
  },
  data() {
    const {
      FormColumns,
      TabColumns,
      TabColumns: [
        {
          item: { key: tabName },
        },
      ],
    } = useColumns();
    const params = this.$init.params(FormColumns);
    const rules = this.$init.rules(FormColumns);
    return {
      rules,
      params: {
        ...params,
        annualGoalMergeDetailsList: [],
        areaDetailList: [],
        customerDetailList: [],
      },
      tabName,
      TabColumns,
      FormColumns,
      visible: false,
      loading: false,
      width: "100%",
      count: 1,
    };
  },
  computed: {
    title: {
      get() {
        const { addType } = this.$props;
        if (addType === "see") {
          return "查 看";
        } else if (addType === "edit") {
          return "编 辑";
        } else {
          return "新 增";
        }
      },
      set() {},
    },
    tableHeight: {
      get() {
        return window.innerHeight - 320;
      },
      set() {},
    },
  },
  watch: {
    "params.goalCategory": {
      handler: function (nVal, oVal) {
        const goal = [
          { title: "销售区域", key: "saleZone" },
          { title: "一级分类", key: "oneLevelClassify" },
          { title: "二级分类", key: "twoLevelClassify" },
        ];

        goal.forEach(({ title, key }) => {
          if (title !== nVal) {
            this.params[key] = null;
            this.params[`${key}Code`] = null;
            this.rules[key] = null;
          } else {
            this.rules[key] = [
              {
                required: true,
                message: `${title}不能为空`,
                trigger: "change",
              },
            ];
          }
        });
        this.count++;
      },
    },
  },
  methods: {
    setVisible(prop) {
      this.visible = prop;
    },
    beforeOpen() {
      const { addType, params, data } = this;
      const { name, nickName, deptName, deptId } = this.$store.state.user;
      if (addType === "add") {
        this.params = {
          ...params,
          deptId,
          dept: deptName,
          creator: nickName,
          creatorCode: name,
          documentDate: new Date().Format("yyyy-MM-dd"),
          annual: new Date().Format("yyyy"),
        };
      } else {
        this.fetchItem(data);
      }
    },
    async fetchItem(prop) {
      try {
        this.$modal.loading("处理中，请稍后...");
        const { id } = prop;
        let { code, mag, data } = await getAnnualSaleGoalMerge(id);
        if (code == 200) {
          this.params = {
            ...data,
            areaDetailList: data.areaDetailList || [],
            customerDetailList: data.customerDetailList || [],
          };
        }
      } catch (error) {
      } finally {
        this.$modal.closeLoading();
      }
    },
    hide() {
      this.visible = false;
      const {
        FormColumns,
        TabColumns: [
          {
            item: { key: tabName },
          },
        ],
      } = useColumns();
      this.params = {
        ...this.$init.params(FormColumns),
        annualGoalMergeDetailsList: [],
        areaDetailList: [],
        customerDetailList: [],
      };
      this.tabName = tabName;
      this.$emit("refresh");
    },
    // 合并
    useMerge(prop) {
      this.$refs[prop].validate(async (valid, obj) => {
        if (valid) {
          const {
            params: { id, annualGoalMergeDetailsList },
            tabName,
          } = this;
          if (id) {
            this.params.oldAnnualGoalMergeDetailsList = _.cloneDeep(
              annualGoalMergeDetailsList
            );
          }
          try {
            let {
              code,
              msg,
              data: { consolidatedDetail },
            } = await mergeAnnualSaleMergeDetails({
              ...this.params,
              annualGoalMergeDetailsList: [],
            });
            if (code == 200) {
              this.params.annualGoalMergeDetailsList = consolidatedDetail;
              this.$notify.success(
                consolidatedDetail.length ? msg : "未查到相关数据"
              );
            }
          } catch (error) {
          } finally {
          }
        } else {
        }
      });
    },
    // 保存
    useSave(prop) {
      console.log(this.params, "this.params");
      this.$refs[prop].validate(async (valid, obj) => {
        if (valid) {
          try {
            const { addType, params } = this;
            let { code, msg } =
              addType == "edit"
                ? await updateAnnualSaleGoalMerge(params)
                : await addAnnualSaleGoalMerge({
                    ...params,
                    status: "0",
                  });
            if (code == 200) {
              this.$notify.success(msg);
              this.hide();
            }
          } catch (error) {
          } finally {
          }
        } else {
          var fail = [];
          for (let key in obj) {
            fail.push(obj[key][0].message);
          }
          this.$notify({
            title: "警告",
            message: fail[0],
            type: "warning",
          });
          return false;
        }
      });
    },
    // 一级分类
    changeOneLevel(row, { prop, columns }) {
      const select = prop[0];
      if (select.code.length > 2) {
        row.oneLevelClassify = null;
        row.oneLevelClassifyCode = null;
        return this.$message.warning("请选择一级分类");
      }
    },
    // 二级分类
    changeTwoLevel(row, { prop, columns }) {
      const select = prop[0];
      if (
        !(select.code.lastIndexOf("-") == 3 || select.code.indexOf("90") == 0)
      ) {
        row.oneLevelClassify = null;
        row.twoLevelClassifyCode = null;
        return this.$message.warning("请选择二级分类");
      }
    },
    // 改变一至十二月份（元）
    changeMonth(prop) {
      const month = [
        "januaryGoal",
        "februaryGoal",
        "marchGoal",
        "aprilGoal",
        "mayGoal",
        "juneGoal",
        "julyGoal",
        "augustGoal",
        "septemberGoal",
        "octoberGoal",
        "novemberGoal",
        "decemberGoal",
      ];
      this.params.goalTotal = this.params["annualGoalMergeDetailsList"].reduce(
        (sum, item) => {
          const rowSum = month.reduce((sum, m) => {
            return (sum += (item[m] ? item[m] : 0) * 1);
          }, 0);
          return (sum += rowSum);
        },
        0
      );
      if (prop) {
        let { row } = prop;
        row["totalGoal"] = month.reduce((sum, item) => {
          return (sum += (row[item] ? row[item] : 0) * 1);
        }, 0);
      }
      // 实时统计
      this.$refs.annualGoalMergeDetailsList[0].updateFooter();
    },
    tabClick({ name }) {
      const { annualGoalMergeDetailsList, areaDetailList, customerDetailList } =
        this.params;
      let arr = _.cloneDeep(annualGoalMergeDetailsList);

      if (name === "annualGoalMergeDetailsList") {
        this.params.areaDetailList = [];
        this.params.customerDetailList = [];
        return;
      }
      // 根据某三个属性进行合并并相加totalGoal的函数
      const mergeAndSumTotalGoal = (array) => {
        return Array.from(
          array
            .reduce((map, obj) => {
              let key = `${obj.saleOrg}-${obj.saleZone}-${
                name === "areaDetailList" ? obj.creator : obj.custom
              }`;

              console.log(key, "key---------------");
              if (map.has(key)) {
                const existingObj = map.get(key);
                existingObj.totalGoal = parseFloat(existingObj.totalGoal);
                existingObj.totalGoal += parseFloat(obj.totalGoal);
                existingObj.totalGoal = existingObj.totalGoal.toFixed(2);
                existingObj.januaryGoal += obj.januaryGoal;
                existingObj.februaryGoal += obj.februaryGoal;
                existingObj.marchGoal += obj.marchGoal;
                existingObj.aprilGoal += obj.aprilGoal;
                existingObj.mayGoal += obj.mayGoal;
                existingObj.juneGoal += obj.juneGoal;
                existingObj.julyGoal += obj.julyGoal;
                existingObj.augustGoal += obj.augustGoal;
                existingObj.septemberGoal += obj.septemberGoal;
                existingObj.octoberGoal += obj.octoberGoal;
                existingObj.novemberGoal += obj.novemberGoal;
                existingObj.decemberGoal += obj.decemberGoal;
              } else {
                map.set(key, {
                  ...obj,
                });
              }
              return map;
            }, new Map())
            .values()
        );
      };

      // 调用合并函数
      const mergedArray = mergeAndSumTotalGoal(arr);
      console.log(name, "name", mergedArray, " mergedArray");

      this.params = {
        ...this.params,
        areaDetailList:
          name === "areaDetailList" ? mergedArray : areaDetailList,
        customerDetailList:
          name === "customerDetailList" ? mergedArray : customerDetailList,
      };
    },
  },
  created() {},
};
</script>

<template>
  <el-drawer
    v-bind="$attrs"
    v-on="$listeners"
    v-loading="loading"
    :size="width"
    :visible.sync="visible"
    destroy-on-close
    :show-close="false"
    @close="hide"
    @open="beforeOpen"
  >
    <div
      slot="title"
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>{{ title }}</h3>
      <div>
        <el-button
          type="primary"
          :size="$attrs.size"
          @click="useSave('superForm')"
          v-if="addType == 'add' || addType == 'edit'"
          >保存</el-button
        >
        <el-button :size="$attrs.size" @click="hide">取消</el-button>
      </div>
    </div>

    <el-super-form
      v-model="params"
      :dict="dict"
      :rules="rules"
      :size="$attrs.size"
      :columns="FormColumns"
      :key="count"
      ref="superForm"
      label-width="auto"
      label-position="right"
      style="padding: 20px"
      :disabled="addType == 'see'"
    >
      <template slot="goalCategory" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="$attrs.size"
          :source.sync="scope.row"
        >
          <el-option
            v-for="item in dict.type[scope.attr.dictName]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </component>
      </template>
      <template slot="saleZone" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="$attrs.size"
          :source.sync="scope.row"
          :disabled="params.goalCategory !== '销售区域'"
        >
        </component>
      </template>
      <template slot="oneLevelClassify" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="$attrs.size"
          :source.sync="scope.row"
          :disabled="params.goalCategory !== '一级分类'"
          @change="
            (prop, columns) => changeOneLevel(scope.row, { prop, columns })
          "
        >
        </component>
      </template>
      <template slot="twoLevelClassify" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="$attrs.size"
          :source.sync="scope.row"
          :disabled="params.goalCategory !== '二级分类'"
          @change="
            (prop, columns) => changeTwoLevel(scope.row, { prop, columns })
          "
        >
        </component>
      </template>
    </el-super-form>

    <el-row
      type="flex"
      justify="end"
      style="margin: 0 20px; position: absolute; right: 0; z-index: 10"
      v-show="addType !== 'see'"
    >
      <el-button
        type="primary"
        :size="$attrs.size"
        @click.native.stop="useMerge('superForm')"
        :disabled="tabName !== 'annualGoalMergeDetailsList'"
        >合 并</el-button
      >
    </el-row>

    <el-tabs
      v-model="tabName"
      @tab-click="tabClick"
      style="margin: 0 20px; position: relative"
    >
      <el-tab-pane
        v-for="({ item, TableColumns: columns }, index) in TabColumns"
        :key="index"
        :label="item.title"
        :name="item.key"
      >
        <el-super-ux-table
          v-model="params[item.key]"
          :dict="dict"
          index
          :ref="tabName"
          :columns="columns"
          :size="$attrs.size"
          :height="tableHeight"
        >
          <!-- 一至十二月 -->
          <template slot="januaryGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="februaryGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="marchGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="aprilGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="mayGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="juneGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="julyGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="augustGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="septemberGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="octoberGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="novemberGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
          <template slot="decemberGoal" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType == 'see'"
              @change="changeMonth(scope)"
            >
            </component>
          </template>
        </el-super-ux-table>
      </el-tab-pane>
    </el-tabs>
  </el-drawer>
</template>

<style scoped>
>>> .el-drawer__header {
  margin-bottom: 0;
  padding: 5px 20px;
}
</style>
