<script>
import useColumns from "./columns";
import {
  getTargetTemplate,
  getHeaderData,
} from "@/api/business/spd/starget/targetTemplate";
import {
  getTarget,
  addTarget,
  updateTarget,
} from "@/api/business/spd/starget/target";

export default {
  name: "targetDetails",
  props: {
    dict: {
      type: Object,
    },
    addType: {
      type: String,
      default: "add",
    },
    row: {
      type: Object,
      required: true,
    },
  },
  components: {
    Item: () => import("../item.vue"),
    ElDictTag: () => import("@/components/DictTag/index.vue"),
    ElSuperForm: () => import("@/components/super-form/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
  },
  data() {
    const { FormColumns, DesColumns } = useColumns();
    const rules = this.$init.rules(FormColumns);
    return {
      width: "100%",
      visible: false,
      loading: false,
      rules,
      DesColumns,
      FormColumns,
      form: {
        date: new Date().Format("yyyy-MM-dd"),
        template: null,
      },
      template: {},
      //子表表头数据
      headers: [],
      //是否展示Item组件
      isItem: false,
      //是否为最新模板
      latestTemplate: false,
    };
  },
  computed: {
    title: {
      get() {
        const { addType } = this;
        if (addType === "edit") {
          return "编 辑";
        }
        if (addType === "see") {
          return "查 看";
        }
        if (addType === "add") {
          return "新 增";
        }
      },
      set() {},
    },
  },
  methods: {
    setVisible(prop) {
      this.visible = prop;
    },
    async beforeOpen() {
      if (this.addType == "add") {
        // this.form.date = new Date();
        this.form.status = "0";
      }
      if (this.addType == "edit" || this.addType == "see") {
        await this.fetchTarget(this.row);
        await this.fetchTemplate(this.row.template);
        await this.fetchHeaderData(this.row.template);
        this.latestTemplate = true;
        this.isItem = true;
      }
    },
    hide() {
      this.isItem = false;
      this.visible = false;
      this.form = {
        date: new Date().Format("yyyy-MM-dd"),
        template: null,
      };
      this.template = {};
      this.headers = [];
      this.$emit("refresh");
    },
    //保存
    async useSave(prop) {
      console.log("this.form", this.form);
      let passrule = false;
      this.$refs[prop].validate((valid) => {
        if (valid) {
          passrule = true;
        }
      });
      if (passrule) {
        try {
          this.form.items = this.$refs.child.merge();
          if (!this.form.items.length) {
            this.$modal.msgError("子表数据不能为空！");
            return;
          }
          console.log("this.form", this.form);
          const { addType, form } = this;
          this.loading = true;
          let res = null;
          if (addType == "add") {
            res = await addTarget(form);
          }
          if (addType == "edit") {
            res = await updateTarget(form);
          }
          if (res.code === 200) {
            this.$modal.msgSuccess(res.msg);
            this.hide();
          }
        } catch (err) {
          // catch
          console.error(err);
        } finally {
          this.loading = false;
        }
      }
    },
    //查询目标模板
    async fetchTemplate(id) {
      try {
        this.loading = true;
        const { code, data } = await getTargetTemplate(id);
        if (code === 200) {
          this.template = data;
          return true;
        } else {
          return false;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //查询详情
    async fetchTarget(row) {
      await getTarget(row.id).then((res) => {
        if (res.code === 200) {
          this.form = res.data;
        }
      });
    },
    //查询动态表头数据
    async fetchHeaderData(id) {
      await getHeaderData(id).then((res) => {
        if (res.code === 200) {
          this.headers = res.rows;
        }
      });
    },
    async changeTemplateName(prop) {
      this.isItem = false;
      await this.fetchTemplate(prop.id);
      await this.fetchHeaderData(prop.id);
      this.isItem = true;
    },
  },
  created() {},
};
</script>
<template>
  <el-drawer
    v-bind="$attrs"
    v-on="$listeners"
    :size="width"
    :visible.sync="visible"
    destroy-on-close
    :show-close="false"
    @close="hide"
    @open="beforeOpen"
    v-loading="loading"
  >
    <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="form"
      :dict="dict"
      :rules="rules"
      :size="$attrs.size"
      :columns="FormColumns"
      ref="superForm"
      label-width="auto"
      label-position="right"
      style="padding: 20px"
      :disabled="addType == 'see'"
    >
      <template slot="templateName" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="$attrs.size"
          :source.sync="scope.row"
          @change="changeTemplateName"
        >
        </component
      ></template>
    </el-super-form>

    <el-card shadow="never" style="margin: 0 20px">
      <el-descriptions title="模板信息">
        <el-descriptions-item
          v-for="({ item, attr }, index) in DesColumns"
          :label="item.title"
        >
          <component
            v-if="item.key === 'cycle' || item.key === 'unfold'"
            v-bind="attr"
            :size="$attrs.size"
            :value="template[item.key]"
            :options="dict.type[attr.dictName]"
          ></component>

          <template v-else-if="item.key === 'dimensionalitys'">
            <div v-for="d in template[item.key]">
              <component
                v-bind="attr"
                :size="$attrs.size"
                :value="d.dimensionality"
                :options="dict.type[attr.dictName]"
              ></component>
            </div>
          </template>
          <template v-else-if="item.key === 'indexs'">
            <div v-for="d in template[item.key]">
              <component
                v-bind="attr"
                :size="$attrs.size"
                :value="d.target"
                :options="dict.type[attr.dictName]"
              ></component>
            </div>
          </template>

          <span v-else>{{ template[item.key] }}</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card
      style="height: calc(100vh - 345px); margin: 10px 20px"
      v-if="isItem"
    >
      <Item
        ref="child"
        :pageStu="addType"
        :template="template"
        :form="form"
        :columns="headers"
        :latestTemplate="latestTemplate"
      ></Item>
    </el-card>
  </el-drawer>
</template>

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