<script>
import useColumns from "./columns";
import { ADD, CODE, LINKAGREEMENT } from "@/api/business/purchase/contract";
import { tax, currency } from "@/components/popover-select-v2/fetch";

export default {
  name: "AddDrawer",
  props: {
    selectData: {
      type: [Array],
      require: true,
    },
    dict: {
      type: Object,
      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.$props;
        if (addType === "add") {
          this.params.source = "自制";
          return "新 增";
        }
        if (addType === "record") {
          this.params.source = "期初补录";
          return "期初补录";
        }
      },
      set() {},
    },
  },
  watch: {
    "params.isRebate": {
      handler: function (newValue) {
        if (newValue === "Y") {
          this.rules.rebatePolicy = [
            { required: true, message: "返利政策不能为空", trigger: "change" },
          ];
        } else {
          this.rules.rebatePolicy = null;
        }
      },
      immediate: true,
    },
    "params.isTarget": {
      handler: function (newValue) {
        if (newValue === "Y") {
          this.rules.contractTarget = [
            { required: true, message: "合同指标不能为空", trigger: "change" },
          ];
        } else {
          this.rules.contractTarget = null;
        }
      },
      immediate: true,
    },
  },
  methods: {
    //
    getTabTableColumnParams(prop) {
      const { TableColumns } = this.TabColumns.find(
        ({ item: { key } }) => key === prop
      );
      return this.$init.params(TableColumns);
    },
    //
    async changePaymentAgreement(prop) {
      const {
        selectData: { code },
      } = prop;
      const { data } = await LINKAGREEMENT(code);
      this.tabName = "contractAgreementList";
      this.params.contractAgreementList.push({
        ...this.getTabTableColumnParams("contractAgreementList"),
        ...data,
      });
    },
    //
    async changeMaterialName(prop) {
      const { row } = prop;
      const { rateCode } = row;
      try {
        // try
        this.loading = true;
        const { ntaxrate } = await tax(rateCode);
        row.tax = Number(ntaxrate === "0E-8" ? 0 : ntaxrate);
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //
    async open() {
      try {
        //
        this.visible = true;
        this.loading = true;
        //
        const {
          user: {
            deptId: puDept,
            deptName: puDeptName,
            name: buyer,
            nickName: buyerName,
            orgId: puOrg,
            orgName: puOrgName,
          },
        } = this.$store.state;
        this.params.puOrg = puOrg;
        this.params.puOrgName = puOrgName;
        this.params.buyer = buyer;
        this.params.buyerName = buyerName;
        this.params.puDept = puDept;
        this.params.puDeptName = puDeptName;
        //
        const { id, code, name } = await currency("人民币");
        this.params.currency = id;
        this.params.currencyCode = code;
        this.params.currencyName = name;
        //
        this.params.code = await CODE();
        //
        this.loading = false;
      } catch (error) {
        this.loading = false;
        this.$notify.error(error);
      }
    },
    //
    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) {
      this.params[prop].push(this.getTabTableColumnParams(prop));
    },
    //
    async useRowRemove(prop, scope) {
      const { $index } = scope;
      this.params[prop].splice($index, 1);
    },
    //
    async useSubmit(prop) {
      this.$refs[prop].validate(async (valid) => {
        if (valid) {
          try {
            // try
            this.loading = true;
            const params = { ...this.params };
            const { msg, code } = await ADD(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" @click="open">
    {{ title }}
    <el-drawer
      :size="width"
      :title="title"
      :visible.sync="visible"
      append-to-body
      destroy-on-close
      :show-close="false"
      @close="hide"
    >
      <div
        slot="title"
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <h3 class="m-0">{{ 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>
      <div
        v-loading="loading"
        style="height: 100%; display: flex; flex-direction: column"
      >
        <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: 18px; flex: 1; overflow-y: auto"
        >
          <template slot="paymentAgreement" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              @change="changePaymentAgreement({ ...scope, selectData: $event })"
            >
            </component>
          </template>
        </el-super-form>

        <el-tabs v-model="tabName" style="margin: 0 18px 18px">
          <el-tab-pane
            v-for="{ item, TableColumns: columns } in TabColumns"
            :key="item.key"
            :label="item.title"
            :name="item.key"
            lazy
          >
            <div style="height: 25vh; display: flex">
              <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="75">
                  <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="useRowRemove(tabName, scope)"
                      >删行
                    </el-button>
                  </template>
                </el-table-column>
              </el-super-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </el-button>
</template>
