<script>
import useColumns from "./columns";
import { initParams, initRules } from "@/utils/init.js";
import { REFER } from "@/components/popover-select/api";
import {
  EDIT,
  ITEM,
  TABLE,
  ALTERATION,
} from "@/api/business/purchase/contract";

export default {
  name: "EditDrawer",
  props: {
    selectData: {
      type: [Array],
      require: true,
    },
    dict: {
      type: Object,
      require: true,
    },
  },
  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(TableColumns);
    const params = this.$init.params([...TabColumns, ...TableColumns]);
    return {
      title: "编 辑",
      width: "100%",
      visible: false,
      loading: false,
      rules: rules,
      params: params,
      tabName: tabName,
      TabColumns: TabColumns,
      TableColumns: TableColumns,
    };
  },
  computed: {
    disabled: {
      get() {
        const { selectData } = this;
        if (selectData.length !== 1) {
          return true;
        }
      },
      set() {},
    },
  },
  watch: {},
  methods: {
    //
    async changeMaterialName(prop) {
      const { row } = prop;
      const { rateCode } = row;
      try {
        // try
        this.loading = true;
        const { code, rows } = await REFER({
          search: rateCode,
          type: "TAX_RATE_PARAM",
        });
        if (code === 200) {
          const [{ ntaxrate }] = rows;
          row.tax = ntaxrate === "0E-8" ? "0.00000000" : ntaxrate;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //
    async fetchItem(prop) {
      try {
        // try
        this.loading = true;
        const { code, data } = await ITEM(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 { selectData } = this.$props;
      const [{ id }] = selectData;
      this.visible = await this.fetchItem(id);
    },
    //
    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 { TableColumns } = this.TabColumns.find(
        ({ item: { key } }) => key === prop
      );
      this.params[prop].push(this.$init.params(TableColumns));
    },
    //
    async useRowRemove(prop, scope) {
      const { REMOVE } = TABLE;
      const {
        $index,
        row: { id, contractId },
      } = scope;
      if (id) {
        try {
          // try
          this.loading = true;
          const { code } = REMOVE(id, prop);
          if (code === 200) {
            this.fetchItem(contractId);
          }
        } catch (err) {
          // catch
          console.error(err);
        } finally {
          // finally
          this.loading = false;
        }
      } else {
        this.params[prop].splice($index, 1);
      }
    },
    //
    async useRowSubmit(prop, scope) {
      const {
        row,
        row: { contractId },
      } = scope;
      const { id } = this.params;
      const { ADD, EDIT } = TABLE;
      try {
        // try
        this.loading = true;
        if (contractId) {
          await EDIT(row, prop);
        } else {
          await ADD({ ...row, contractId: id }, prop);
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.fetchItem(id);
        this.loading = false;
      }
    },
    //
    async useSubmit(prop) {
      this.$refs[prop].validate(async (valid) => {
        if (valid) {
          try {
            // try
            this.loading = true;
            const {
              params,
              params: { status },
            } = this;
            const TASK = status === "2" ? EDIT : ALTERATION;
            const { msg, code } = await TASK(params);
            if (code === 200) {
              this.hide();
              this.$emit("success");
              this.$notify.success(msg);
            }
          } catch (err) {
            // catch
            console.error(err);
          } finally {
            // finally
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
  },
  created() {},
  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
      :show-close="false"
      destroy-on-close
      @close="hide"
    >
      <div
        slot="title"
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <h3>{{ title }}</h3>
        <div style="text-align: right">
          <el-button
            type="primary"
            :size="$attrs.size"
            :loading="loading"
            @click="useSubmit('superForm')"
            >确 认</el-button
          >
          <el-button :size="$attrs.size" :loading="loading" @click="hide"
            >取 消</el-button
          >
        </div>
      </div>
      <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"
      ></el-super-form>
      <el-tabs v-model="tabName" style="margin: 0 20px">
        <el-tab-pane
          v-for="{ item, TableColumns: columns } in TabColumns"
          :key="item.key"
          :label="item.title"
          :name="item.key"
          lazy
        >
          <el-super-table
            v-model="params[item.key]"
            :dict="dict"
            :ref="tabName"
            :columns="columns"
            :size="$attrs.size"
            index
          >
            <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="100">
              <template slot="header" slot-scope="scope">
                <el-button
                  type="text"
                  :size="$attrs.size"
                  @click="useRowAdd(tabName)"
                  >增行
                </el-button>
              </template>
              <template slot-scope="scope">
                <el-button
                  type="text"
                  :size="$attrs.size"
                  @click.native.prevent="useRowSubmit(tabName, scope)"
                  >更新
                </el-button>
                <el-button
                  type="text"
                  :size="$attrs.size"
                  @click.native.prevent="useRowRemove(tabName, scope)"
                  >删行
                </el-button>
              </template>
            </el-table-column>
          </el-super-table>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </el-button>
</template>
