<!-- 年度销售目标填报-详情 -->
<script>
import useColumns from "./columns";
import { importData } from "@/api/business/spd/goal_management/annualSaleGoalDetails";
import {
  getAnnualSaleGoal,
  addAnnualSaleGoal,
  updateAnnualSaleGoal,
} from "@/api/business/spd/goal_management/annualSaleGoal";

export default {
  name: "annualSaleGoalDetails",
  props: {
    dict: {
      type: Object,
    },
    data: {
      type: Object,
    },
    addType: {
      type: String,
      default: "add",
    },
  },
  components: {
    BatchUpdate: () => import("../batchUpdate/index.vue"),
    ElSuperForm: () => import("@/components/super-form/index.vue"),
    BatchImport: () => import("@/components/BatchImport/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
  },
  data() {
    const {
      FormColumns,
      TabColumns,
      TabColumns: [
        {
          item: { key: tabName },
        },
      ],
    } = useColumns();
    const params = this.$init.params(FormColumns);
    const rules = this.$init.rules(FormColumns);
    return {
      width: "100%",
      visible: false,
      loading: false,
      params: {
        ...params,
        annualGoalMergeDetails: [],
      },
      rules,
      tabName,
      TabColumns,
      FormColumns,
    };
  },
  computed: {
    title: {
      get() {
        const { addType } = this.$props;
        if (addType === "see") {
          return "查 看";
        } else if (addType === "edit") {
          return "编 辑";
        } else {
          return "新 增";
        }
      },
      sest() {},
    },
    tableHeight: {
      get() {
        return window.innerHeight - 320;
      },
      set() {},
    },
  },
  methods: {
    setVisible(prop) {
      this.visible = prop;
    },
    // 关闭
    hide() {
      this.visible = false;
      const {
        FormColumns,
        TabColumns: [
          {
            item: { key: tabName },
          },
        ],
      } = useColumns();
      this.params = {
        ...this.$init.params(FormColumns),
        annualGoalMergeDetails: [],
      };
      this.tabName = tabName;
      this.$emit("refresh");
    },
    //
    beforeOpen() {
      const { addType, data } = this.$props;
      const { name, nickName, deptId, deptName } = this.$store.state.user;
      if (addType === "add") {
        this.params = {
          ...this.params,
          creator: nickName,
          creatorCode: name,
          dept: deptName,
          deptId,
          annual: new Date().Format("yyyy"),
          documentDate: new Date().Format("yyyy-MM-dd"),
          goalTotal: 0,
        };
        this.addRow(this.tabName);
      } else {
        this.fetchItem(data);
      }
    },
    //
    async fetchItem(prop) {
      try {
        this.loading = true;
        const { id } = prop;
        let { code, data } = await getAnnualSaleGoal(id);
        if (code == 200) {
          this.params = data;
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    // 保存
    useSave(prop) {
      console.log(this.params, "params");
      this.$refs[prop].validate(async (valid, obj) => {
        if (valid) {
          try {
            const {
              params,
              params: { saleZone, custom, creator },
              $props: { addType },
            } = this;
            const { orgName: saleOrg } = this.$store.state.user;
            const data = {
              ...params,
              annualGoalMergeDetails: params.annualGoalMergeDetails.map(
                (item) => ({
                  ...item,
                  saleOrg: item.saleOrg ? item.saleOrg : orgName,
                  saleZone: item.saleZone ? item.saleZone : saleZone,
                  custom: item.custom ? item.custom : custom,
                  creator: item.creator ? item.creator : creator,
                })
              ),
            };
            let { code, msg } =
              addType === "add"
                ? await addAnnualSaleGoal(data)
                : await updateAnnualSaleGoal(data);
            if (code == 200) {
              this.$notify.success(msg);
              this.hide();
            }
          } catch (error) {}
        } else {
          var fail = [];
          for (let key in obj) {
            fail.push(obj[key][0].message);
          }
          this.$notify({
            title: "警告",
            message: fail[0],
            type: "warning",
          });
          return false;
        }
      });
    },
    // 增行
    addRow(tabName) {
      const { orgName } = this.$store.state.user;
      const { saleZone, custom, creator } = this.params;
      const { TableColumns } = this.TabColumns.find(
        ({ item: { key } }) => key === tabName
      );
      this.params[tabName].push({
        ...this.$init.params(TableColumns),
        delFlag: "0",
        saleOrg: orgName,
        saleZone,
        custom,
        creator,
      });
    },
    // 删行
    delRow(prop, tabName) {
      const { row, $rowIndex } = prop;
      this.params[tabName] = this.params[tabName].filter(
        (item, index) => index !== $rowIndex
      );
    },
    changeMaterial({ row, selectData: { oneClass, twoClass } }) {
      row.oneLevelClassifyCode = oneClass && oneClass.split("&")[1];
      row.twoLevelClassifyCode = twoClass && twoClass.split("&")[1];
    },
    // 改变一至十二月份（元）
    changeMonth(prop) {
      const month = [
        "januaryGoal",
        "februaryGoal",
        "marchGoal",
        "aprilGoal",
        "mayGoal",
        "juneGoal",
        "julyGoal",
        "augustGoal",
        "septemberGoal",
        "octoberGoal",
        "novemberGoal",
        "decemberGoal",
      ];
      this.params.goalTotal = this.params["annualGoalMergeDetails"].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.annualGoalMergeDetails[0].updateFooter();
    },
    // 导入
    async handelImport(fileList) {
      try {
        this.$modal.loading("正在上传文件，请稍候...");

        let formData = new FormData();
        formData.append("file", fileList[0].raw);
        let { code, msg, data } = await importData(formData);
        if (code == 200) {
          this.params["annualGoalMergeDetails"] = [
            ...this.params["annualGoalMergeDetails"],
            ...data,
          ];

          let { setVisible } = this.$refs.batchImport;
          setVisible(false);
          this.changeMonth();
          this.$notify.success(msg);
        }
      } catch (error) {
      } finally {
        this.$modal.closeLoading();
      }
    },
    // 模板下载
    handleTemDownload() {
      this.download(
        "/goal_management/annualSaleGoalDetails/importTemplate",
        {},
        `年销售目标填报明细导入模板_${new Date().getTime()}.xlsx`
      );
    },
    // 批量更新
    useUpdate(prop) {
      const { key, value } = prop;
      this.params["annualGoalMergeDetails"].forEach((item) => {
        item[key] = value;
      });
    },
  },
  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"
      ref="superForm"
      label-width="auto"
      label-position="right"
      style="padding: 20px"
      :disabled="addType == 'see'"
    >
    </el-super-form>

    <el-row
      type="flex"
      justify="end"
      style="margin: 0 20px"
      v-show="addType !== 'see'"
    >
      <batch-import
        ref="batchImport"
        :fileSize="2"
        :size="$attrs.size"
        @import="handelImport"
        @temDownload="handleTemDownload"
      ></batch-import>
      <batch-update
        :size="$attrs.size"
        type="primary"
        @confirm="useUpdate"
      ></batch-update>
    </el-row>

    <el-tabs v-model="tabName" style="margin: 0 20px">
      <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
          showSummary
          :ref="tabName"
          :columns="columns"
          :size="$attrs.size"
          :height="tableHeight"
        >
          <!-- 物料 -->
          <template slot="material" 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="changeMaterial({ ...scope, selectData: $event })"
            >
            </component>
          </template>
          <!-- 一至十二月 -->
          <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>
          <ux-table-column
            v-if="addType !== 'see'"
            fixed="right"
            title="操作"
            width="120"
            align="center"
          >
            <template slot="header" slot-scope="scope">
              <el-button
                type="text"
                :size="$attrs.size"
                @click="addRow(tabName)"
                >增 行</el-button
              >
            </template>
            <template slot-scope="scope">
              <el-button
                type="text"
                :size="$attrs.size"
                @click.native.prevent="delRow(scope, tabName)"
                >删 行</el-button
              >
            </template>
          </ux-table-column>
        </el-super-ux-table>
      </el-tab-pane>
    </el-tabs>
  </el-drawer>
</template>

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