<script>
import useColumns from "./columns";
import { EXIST } from "@/api/business/purchase/catalogue";
import { ITEM, 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: "EditDrawer",
  props: {
    dict: {
      type: Object,
    },
    selectData: {
      type: [Array],
      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([...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: {
    disabled: {
      get() {
        const {
          selectData,
          selectData: [{ status } = {}],
        } = this.$props;
        if (selectData.length !== 1) {
          return true;
        }
        if (selectData.length === 1 && status === "1") {
          return true;
        }
        if (selectData.length === 1 && status === "2") {
          return true;
        }
      },
      set() {},
    },
    priceApply: {
      get() {
        this.params.priceApplyItems = this.params.priceApplyItems.map(
          (item, index) => ({
            ...item,
            $index: index,
          })
        );
        return {
          priceApplyItems: this.params.priceApplyItems.filter(
            ({ delFlag }) => delFlag !== "2"
          ),
        };
      },
      set() {},
    },
  },
  watch: {},
  methods: {
    //
    changeMaterialName(prop) {
      console.log(prop, "prop");
      const { row } = prop;
      const { puOrg, customer, supplier } = this.params;
      const { tax: taxName, unitName, code: materialCode } = row;
      // task 1
      tax(taxName).then((res) => {
        const { ntaxrate } = res;
        row.tax = ntaxrate === "0E-8" ? "0.000000" : (ntaxrate * 1).toFixed(6);
      });
      // task 2
      unit(unitName).then((res) => {
        const { id, code, name } = res;
        row.unit = id;
        row.unitCode = code;
        row.unitName = name;
        row.puUnit = id;
        row.puUnitCode = code;
        row.puUnitName = name;
      });
      // task 3
      currency("人民币").then((res) => {
        const { id, code, name } = res;
        row.currency = id;
        row.currencyCode = code;
        row.currencyName = name;
      });
      // task 4
      fetchExist({ puOrg, customer, supplier, materialCode }).then((res) => {
        const { recentlyPrice, isApprovalFirst, isPriceAdjustment } = res;
        row.recentlyPrice = recentlyPrice;
        row.isApprovalFirst = isApprovalFirst;
        row.isPriceAdjustment = isPriceAdjustment;
      });
    },
    //
    async fetchItem(prop) {
      try {
        // try
        this.loading = true;
        const { tabName, TabColumns } = this;
        const { TableColumns } = TabColumns.find(
          ({ item: { key } }) => key === tabName
        );
        const { code, data } = await ITEM(prop);
        if (code === 200) {
          this.params = data;
          this.params.priceApplyItems = data.priceApplyItems.map((item) => ({
            ...this.$init.params(TableColumns),
            ...item,
          }));
          return true;
        } else {
          return false;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //
    async onOpen() {
      const {
        selectData: [{ id }],
      } = this.$props;
      this.visible = await this.fetchItem(id);
    },
    //
    async onHide() {
      const { TabColumns, TableColumns } = useColumns();
      this.visible = false;
      this.params = this.$init.params([...TabColumns, ...TableColumns]);
    },
    //
    async onRowAdd(prop) {
      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),
      });
    },
    //
    async onRowRemove(prop, scope) {
      const {
        row: { $index },
      } = scope;
      this.params[prop] = this.params[prop].map((item, index) => ({
        ...item,
        delFlag: index === $index ? "2" : item.delFlag,
      }));
    },
    //
    async useSubmit(prop) {
      this.$refs[prop].validate(async (valid) => {
        console.log(this.params);
        if (valid) {
          try {
            this.loading = true;
            this.params.priceApplyItems = this.params.priceApplyItems.filter(
              (item) => item.materialName
            );
            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"
    :disabled="disabled"
    @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"
      >
        <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="priceApply[item.key]"
            :dict="dict"
            :ref="tabName"
            :columns="columns"
            :size="$attrs.size"
            style="padding: 20px 10px;height: 400px;"
          >
            <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 :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>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </el-button>
</template>

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