<template>
  <div>
    <el-row>
      <div class="btn_add">
        <!-- <el-button type="primary" size="mini" @click="useTemplateDownload" v-if="this.pageStu != 'see'">下载模板</el-button>
        <el-button type="primary" size="mini" @click="useAdd" v-if="this.pageStu != 'see'">导入</el-button> -->
        <el-button
          type="primary"
          size="mini"
          @click="useAdd"
          v-if="this.pageStu != 'see'"
          >增行</el-button
        >
      </div>
    </el-row>
    <!-- 渲染表头 -->
    <el-table :data="items" :height="height" v-horizontal-scroll>
      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        fixed
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        v-for="head in headers"
        :prop="head.prop"
        :label="head.modelName"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          <div v-if="pageStu == 'add' || pageStu == 'edit'">
            <div v-if="scope.row[head.prop].type == 'D'">
              <dr-popover-select
                size="mini"
                v-if="
                  scope.row[head.prop].model == 'MK_TARGET_CYCLE_PARAM' ||
                  scope.row[head.prop].model == 'MK_TARGET_INDEX_PARAM'
                "
                v-model="scope.row[head.prop].valueName"
                title="参照选择"
                :type="scope.row[head.prop].model"
                :dataMapping="{
                  value: 'id',
                  valueName: 'name',
                }"
                :source.sync="scope.row[head.prop]"
                :queryParams="additionalCondition"
              />
              <el-popover-tree-select
                size="mini"
                v-else-if="
                  scope.row[head.prop].model == 'MATERIALCLASSIFY_PARAM' ||
                  scope.row[head.prop].model == 'PROFITCENTER' ||
                  scope.row[head.prop].model == 'PRODUCTLINE'
                "
                v-model="scope.row[head.prop].valueName"
                valueKey="name"
                title="参照选择"
                :referName="scope.row[head.prop].model"
                :dataMapping="{
                  value: 'id',
                  valueName: 'name',
                }"
                :source.sync="scope.row[head.prop]"
              >
              </el-popover-tree-select>
              <dr-popover-select
                size="mini"
                v-else
                v-model="scope.row[head.prop].valueName"
                title="参照选择"
                :type="scope.row[head.prop].model"
                :dataMapping="{
                  value: 'id',
                  valueName: 'name',
                }"
                :source.sync="scope.row[head.prop]"
              >
              </dr-popover-select>
            </div>
            <div
              v-if="
                scope.row[head.prop].type == 'C' ||
                scope.row[head.prop].type == 'I'
              "
            >
              <el-input
                size="mini"
                v-model="scope.row[head.prop].value"
                class="input-view"
                oninput="value=value.replace(/[^0-9]/g,'')"
              ></el-input>
            </div>
          </div>
          <div v-else-if="pageStu == 'see'">
            <div v-if="scope.row[head.prop].type == 'D'">
              {{ scope.row[head.prop].valueName }}
            </div>
            <div v-else>
              {{ scope.row[head.prop].value }}
            </div>
          </div>
        </template>
        <el-table-column
          show-overflow-tooltip
          v-if="head.children"
          v-for="headChi in head.children"
          :prop="headChi.prop"
          :label="headChi.modelName"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            <div v-if="pageStu == 'add' || pageStu == 'edit'">
              <!-- <el-input size="mini" v-model="scope.row[headChi.prop].value" class="input-view" oninput="value=value.replace(/[^0-9]/g,'')"></el-input> -->
              <el-input-number
                size="mini"
                v-model="scope.row[headChi.prop].value"
                :precision="2"
                class="input-view"
                oninput="value=value.replace(/[^0-9]/g,'')"
              ></el-input-number>
            </div>
            <div v-else-if="pageStu == 'see'">
              {{ scope.row[headChi.prop].value }}
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        v-if="this.pageStu != 'see'"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="useDel(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getTargetItem } from "@/api/business/spd/starget/target";

export default {
  name: "item",
  props: ["pageStu", "template", "form", "columns", "latestTemplate"],
  dicts: [
    "sys_yes_no",
    "mk_periodic_unit",
    "mk_dimensionality",
    "mk_index_type",
    "mk_expansion_mode",
  ],
  components: {
    ElPopoverTreeSelect: () =>
      import("@/components/popover-tree-select/index.vue"),
  },
  data() {
    return {
      items: [],
      delItems: [],
      headers: [],
      itemTemplate: {},
    };
  },
  computed: {
    height: {
      get() {
        return window.innerHeight - 410;
      },
      set() {},
    },
  },
  async created() {
    this.processHeadersData(this.template.unfold, this.columns);
    this.itemTemplate = this.formatItem(this.columns);
    if (this.pageStu == "edit" || this.pageStu == "see") {
      if (this.latestTemplate) {
        await this.fetchTargetItem(this.form.id);
      }
    }
  },
  methods: {
    //增行
    useAdd() {
      let obj = JSON.parse(JSON.stringify(this.itemTemplate));
      this.items.push(obj);
      console.log("this.items", this.items);
    },
    //删行
    useDel(index) {
      this.items[index].delFlag = "2";
      if (this.items[index].id) {
        let delList = this.items.filter((item) => {
          return item.delFlag == "2";
        });
        this.delItems.push(...delList);
      }
      this.items.splice(index, 1);
    },
    //下载模板
    useTemplateDownload() {
      try {
        this.download(
          "/mk/target/targetTemplate/download/" + this.template.id,
          {},
          `营销目标_${new Date().getTime()}.xlsx`
        );
      } catch (err) {
        console.error(err);
      } finally {
      }
    },
    //表头数据处理
    processHeadersData(unfold, columns) {
      const array = [];
      if ("cycle/unfold" == unfold) {
        for (let i in columns) {
          if (columns[i].type == "D") {
            columns[i].prop = columns[i].model;
            array.push(columns[i]);
          } else {
            const arr = array.filter(
              (element) => element.model == columns[i].superiors
            );
            if (arr.length > 0) {
              columns[i].prop =
                array[array.length - 1].model + "-" + columns[i].model;
              array[array.length - 1].children.push(columns[i]);
            } else {
              columns[i].prop = columns[i].superiors + "-" + columns[i].model;
              let c = {
                type: "C",
                model: columns[i].superiors,
                modelName: columns[i].superiorsName,
                children: [columns[i]],
              };
              array.push(c);
            }
          }
        }
        this.headers = array;
      } else if ("cycle" == unfold) {
        for (let i in columns) {
          columns[i].prop = columns[i].model;
          if (
            columns[i].model == "MK_TARGET_CYCLE_PARAM" ||
            columns[i].model == "MK_TARGET_INDEX_PARAM"
          ) {
            columns[i].templateId = this.template.id;
          }
          array.push(columns[i]);
        }
        this.headers = array;
      } else if ("unfold" == unfold) {
        for (let i in columns) {
          columns[i].prop = columns[i].model;
          if (
            columns[i].model == "MK_TARGET_CYCLE_PARAM" ||
            columns[i].model == "MK_TARGET_INDEX_PARAM"
          ) {
            columns[i].templateId = this.template.id;
          }
          array.push(columns[i]);
        }
        this.headers = array;
      } else if ("" == unfold) {
        for (let i in columns) {
          columns[i].prop = columns[i].model;
          if (
            columns[i].model == "MK_TARGET_CYCLE_PARAM" ||
            columns[i].model == "MK_TARGET_INDEX_PARAM"
          ) {
            columns[i].templateId = this.template.id;
          }
          array.push(columns[i]);
        }
        this.headers = array;
      }
      console.log("this.headers", this.headers);
    },
    //获取明细数据
    async fetchTargetItem(id) {
      await getTargetItem(id).then((res) => {
        if (res.code === 200) {
          this.items = res.rows;
        }
      });
    },
    //格式化数据
    formatItem(item) {
      let obj = {};
      for (let i in item) {
        obj[item[i].prop] = item[i];
      }
      return obj;
    },
    //合并已存在和删除的数据
    merge() {
      console.log("this.items", this.items);
      this.items.push(...this.delItems);
      return this.items;
    },
    //附加查询条件
    additionalCondition(prop) {
      console.log("prop", prop);
      return {
        parame: {
          templateId: prop.templateId,
        },
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.btn_add {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}
.btn_group {
  width: 100%;
  margin: 20px 0;
  display: flex;
  justify-content: center;
}
</style>
