<script>
import useColumns from "./columns";
import { EXIST } from "@/api/business/purchase/catalogue";
import { SAVE } from "@/api/business/purchase/apply";
import { tax, unit, currency } from "@/components/popover-select-v2/fetch";

const fetchExist = async (prop) => {
  try {
    // try
    const { code, data } = await EXIST(prop);
    if (code === 200) return data;
  } catch (err) {
    // catch
    console.error(err);
  } finally {
    // finally
  }
};

export default {
  name: "AddDrawer",
  props: {
    dict: {
      type: Object,
    },
  },
  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 {
      title: "新 增",
      width: "100%",
      visible: false,
      loading: false,
      rules: rules,
      params: params,
      tabName: tabName,
      TabColumns: TabColumns,
      TableColumns: TableColumns,
    };
  },
  computed: {},
  watch: {},
  methods: {
    //
    async changeMaterialName(prop) {
      const { selectData } = prop;
      const {
        puOrg,
        customer,
        supplier,
        currency,
        currencyCode,
        currencyName,
      } = this.params;
      if (selectData.length) {
        this.params[this.tabName].splice(-1);
      }
      for (const item of selectData) {
        const { tax: taxName, unitName, code: materialCode } = item;
        // task 1
        const { ntaxrate } = await tax(taxName);
        // task 2
        const {
          id: puUnit,
          code: puUnitCode,
          name: puUnitName,
        } = await unit(unitName);
        // task 3
        const {
          recentlyPrice = "0",
          isApprovalFirst = "N",
          isPriceAdjustment = "N",
        } = await fetchExist({ puOrg, customer, supplier, materialCode });
        await this.onRowAdd(this.tabName, {
          ...item,
          currency: currency,
          currencyCode: currencyCode,
          currencyName: currencyName,
          unit: puUnit,
          unitCode: puUnitCode,
          unitName: puUnitName,
          puUnit: puUnit,
          puUnitCode: puUnitCode,
          puUnitName: puUnitName,
          recentlyPrice,
          isApprovalFirst,
          isPriceAdjustment,
          tax: Number(ntaxrate === "0E-8" ? 0 : ntaxrate).toFixed(6),
        });
      }
    },
    //
    async onOpen() {
      this.visible = true;
      const {
        deptId: puDept,
        deptName: puDeptName,
        name: buyer,
        nickName: buyerName,
      } = this.$store.state.user;
      const { id, code, name } = await currency("人民币");
      this.params.currency = id;
      this.params.currencyCode = code;
      this.params.currencyName = name;
      this.params.buyer = buyer;
      this.params.buyerName = buyerName;
      this.params.puDept = puDept;
      this.params.puDeptName = puDeptName;
    },
    //
    async onHide() {
      const { TabColumns, TableColumns } = useColumns();
      this.visible = false;
      this.params = this.$init.params([...TabColumns, ...TableColumns]);
    },
    //
    async onRowAdd(prop, pushParams = {}) {
      const {
        $notify,
        TabColumns,
        params: { puOrgName, supplierName },
      } = this;
      if (!supplierName) {
        return $notify.info("请选择供应商");
      }
      if (!puOrgName) {
        return $notify.info("请选择采购组织");
      }
      const { TableColumns } = TabColumns.find(
        ({ item: { key } }) => key === prop
      );
      this.params[prop].push({
        delFlag: "0",
        ...this.$init.params(TableColumns),
        ...pushParams,
      });
    },
    //
    async onRowRemove(prop, scope) {
      const { $index } = scope;
      this.params[prop].splice($index, 1);
    },
    //
    async useSubmit(prop) {
      this.$refs[prop].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            const { msg, code } = await SAVE(this.params);
            if (code === 200) {
              this.onHide();
              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" @click="onOpen">
    {{ title }}
    <el-drawer
      :show-close="false"
      :size="width"
      :title="title"
      :visible.sync="visible"
      append-to-body
      destroy-on-close
      @close="onHide"
    >
      <template slot="title">
        <span>{{ title }}</span>
        <el-button
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="useSubmit('superForm')"
        >
          确 认
        </el-button>
        <el-button :size="$attrs.size" :loading="loading" @click="onHide">
          取 消
        </el-button>
      </template>
      <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="padding: 0 20px 20px">
        <el-tab-pane
          v-for="({ item, TableColumns: columns }, index) in TabColumns"
          :key="index"
          :label="item.title"
          :name="item.key"
          lazy
        >
          <div v-loading="loading" style="height: 600px; display: flex">
            <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, selectData: $event })"
                >
                </component>
              </template>
              <el-table-column fixed="right" label="操作" width="100">
                <template slot="header" slot-scope="scope">
                  <el-button :size="$attrs.size" @click="onRowAdd(tabName)">
                    新增
                  </el-button>
                </template>
                <template slot-scope="scope">
                  <el-button
                    :size="$attrs.size"
                    @click.native.prevent="onRowRemove(tabName, scope)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-super-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </el-button>
</template>

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