<script>
import useColumns from "./columns";
import {
  addTargetTemplate,
  updateTargetTemplate,
  getTargetTemplate,
  checkQuote,
} from "@/api/business/spd/starget/targetTemplate";
export default {
  name: "AddDrawer",
  props: {
    dict: {
      type: Object,
    },
    selectData: {
      type: [Array],
      require: true,
    },
    addType: {
      type: String,
      default: "add",
    },
  },
  components: {
    ElSuperForm: () => import("@/components/super-form/index.vue"),
    ElSuperTable: () => import("@/components/super-table/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
  },
  data() {
    const {
      TabColumns,
      TableColumns,
      TabColumns: [
        {
          item: { key: tabName },
        },
      ],
    } = useColumns();
    const rules = this.$init.rules([...TabColumns, ...TableColumns]);
    const params = this.$init.params([...TabColumns, ...TableColumns]);
    return {
      width: "100%",
      visible: false,
      loading: false,
      rules: rules,
      params: params,
      tabName: tabName,
      TabColumns: TabColumns,
      TableColumns: TableColumns,
    };
  },
  computed: {
    title: {
      get() {
        const { addType } = this;
        if (addType === "add") {
          return "新 增";
        }
        if (addType === "edit") {
          return "编 辑";
        }
      },
      set() {},
    },
    disabled: {
      get() {
        const {
          addType,
          selectData,
          selectData: [{ status } = {}],
        } = this.$props;
        if (addType === "add") {
          return false;
        }
        if (addType === "edit") {
          if (selectData.length !== 1) {
            return true;
          }
          if (selectData.length === 1 && status === "1") {
            return true;
          }
          if (selectData.length === 1 && status === "2") {
            return true;
          }
        }
      },
      set() {},
    },
  },
  watch: {},
  methods: {
    changePuOrgName(prop) {
      console.log("changePuOrgName", prop);
    },
    changeMaterialName(prop) {
      console.log("changeMaterialName", prop);
    },

    //查询目标模板详情
    async fetchTemplate(prop) {
      try {
        // try
        this.loading = true;
        const { code, data } = await getTargetTemplate(prop);
        if (code === 200) {
          this.params = data;
          return true;
        } else {
          return false;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //打开组件
    async open() {
      const { addType, selectData } = this.$props;
      if (addType === "add") {
        this.visible = true;
      }
      if (addType === "edit") {
        const [{ id }] = selectData;
        //校验目标模板是否存在引用
        const { code, data } = await checkQuote(id);
        if(code == '200'){
          if(data){
            this.$modal.msgError("该目标模板存在引用，无法修改！");
            this.visible = false;
            return;
          }
        }else{
          this.$modal.msgError("校验该目标模板是否存在引用异常，无法修改！");
          this.visible = false;
          return;
        }
        this.visible = await this.fetchTemplate(id);
        this.params.indexs = this.params.indexs.map((item) => ({ ...item }));
        this.params.dimensionalitys = this.params.dimensionalitys.map(
          (item) => ({ ...item })
        );
        this.params.cycles = this.params.cycles.map((item) => ({ ...item }));
      }
    },
    //关闭页面
    async hide() {
      const {
        TabColumns,
        TableColumns,
        TabColumns: [
          {
            item: { key: tabName },
          },
        ],
      } = useColumns();
      this.visible = false;
      this.tabName = tabName;
      this.params = this.$init.params([...TabColumns, ...TableColumns]);
    },
    //增行
    async useRowAdd(prop) {
      const { TabColumns } = this;
      const { TableColumns } = TabColumns.find(
        ({ item: { key } }) => key === prop
      );
      console.log(prop, this.$init.params(TableColumns));
      this.params[prop].push({
        delFlag: "0",
        ...this.$init.params(TableColumns),
      });
      console.log("this.params[prop]", this.params[prop]);
    },
    //删行
    async useRowRemove(prop, scope) {
      const { addType } = this.$props;
      const {
        row: { $index },
      } = scope;
      if (addType === "add") {
        this.params[prop].splice($index, 1);
      }
      if (addType === "edit") {
        this.params[prop] = this.params[prop].map((item, index) => ({
          ...item,
          delFlag: index === $index ? "2" : item.delFlag,
        }));
        console.log(this.params[prop]);
      }
    },
    //确认
    async useSubmit(prop) {
      this.$refs[prop].$refs[prop].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            // const {
            //   params,
            //   params: { paramsOrgs, paramsItems },
            // } = this;
            // if (this.addType === "edit") {
            //   params.paramsOrgs = paramsOrgs.filter(
            //     (item) => item.orgName
            //   );
            //   params.paramsItems = paramsItems.filter(
            //     (item) => item.materialName
            //   );
            // }
            const { addType } = this.$props;
            let res = null;
            if (addType === "add") {
              res = await addTargetTemplate(this.params);
            }
            if (addType === "edit") {
              res = await updateTargetTemplate(this.params);
            }
            if (res.code === 200) {
              this.hide();
              this.$emit("success");
              this.$notify.success(res.msg);
            }
          } catch (err) {
            // catch
            console.error(err);
          } finally {
            // finally
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
  },
  created() {
    console.log("params", this.params);
  },
  mounted() {},
  destroyed() {},
};
</script>
<template>
  <el-button
    v-bind="$attrs"
    v-on="$listeners"
    :disabled="disabled"
    @click="open"
  >
    {{ title }}
    <el-drawer
      :size="width"
      :title="title"
      :visible.sync="visible"
      append-to-body
      destroy-on-close
      @close="hide"
    >
      <el-super-form
        v-model="params"
        :dict="dict"
        :rules="rules"
        :size="$attrs.size"
        :columns="TableColumns"
        ref="superForm"
        label-width="auto"
        label-position="right"
        style="padding: 20px"
      >
        <!-- <template slot="puOrgName" slot-scope="scope">
          <component
            v-bind="scope.attr"
            v-model="scope.row[scope.item.key]"
            :size="$attrs.size"
            :source.sync="scope.row"
            @change="changePuOrgName({ ...scope, select: $event })"
          >
          </component
        ></template> -->
      </el-super-form>
      <el-tabs v-model="tabName" style="padding: 0 20px 20px">
        <el-tab-pane
          v-for="({ item, TableColumns: columns }, index) in TabColumns"
          :key="index"
          :label="item.title"
          :name="item.key"
          lazy
        >
          <el-super-table
            v-model="params[item.key]"
            :dict="dict"
            :ref="tabName"
            :columns="columns"
            :size="$attrs.size"
          >
            <!-- <template slot="materialName" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                @change="changeMaterialName(scope)"
              >
              </component>
            </template> -->
            <el-table-column fixed="right" label="操作" width="75">
              <template slot="header" slot-scope="scope">
                <el-button
                  circle
                  icon="el-icon-plus"
                  :size="$attrs.size"
                  @click="useRowAdd(tabName)"
                >
                </el-button>
              </template>
              <template slot-scope="scope">
                <el-button
                  circle
                  icon="el-icon-minus"
                  :size="$attrs.size"
                  @click.native.prevent="useRowRemove(tabName, scope)"
                >
                </el-button>
              </template>
            </el-table-column>
          </el-super-table>
        </el-tab-pane>
      </el-tabs>
      <div style="padding: 20px; text-align: right">
        <el-button :size="$attrs.size" :loading="loading" @click="hide"
          >取 消</el-button
        >
        <el-button
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="useSubmit('superForm')"
          >确 认</el-button
        >
      </div>
    </el-drawer>
  </el-button>
</template>

<style scoped>
::v-deep .el-table__row.is-hidden {
  display: none;
}
</style>
