<script>
import useColumns from "./columns";
import {
  EDIT,
  ITEM,
  TABLE,
  ALTERATION,
} from "@/api/business/purchase/contract";
import { tax } from "@/components/popover-select-v2/fetch";

export default {
  name: "EditFormModel",
  props: {
    selectData: {
      type: [Array],
      require: true,
    },
    dict: {
      type: Object,
      require: true,
    },
    title: {
      type: String,
    },
  },
  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 {
      loading: false,
      loadingText: "",
      rules: rules,
      params: params,
      tabName: tabName,
      TabColumns: TabColumns,
      TableColumns: TableColumns,
    };
  },
  computed: {
    id: {
      get() {
        return this.$props.selectData[0].id;
      },
      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,
    },
    "params.status":{
      handler:function(newValue){

        if(newValue === '2'){
          // 已审核
          this.TableColumns = this.TableColumns.map(({item,attr}) =>{

            return {
              item:{...item},
              attr:{
                ...attr,
                disabled: item.key !== 'puFile' ? true: false
              }
            }

          })
        }
      }
    }
  },
  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);
        row.tax = ntaxrate === "0E-8" ? 0 : ntaxrate;
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //
    async fetchItem(prop) {
      try {
        // try
        this.loading = true;
        this.loadingText = "获取合同中";
        const { code, data } = await ITEM(prop);
        if (code === 200) {
          this.params = data;
        } else {
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //
    async open() {
      await this.fetchItem(this.id);
    },
    //
    async hide() {
      this.$emit("close");
    },
    //
    async useRowAdd(prop) {
      this.params[prop].push(this.getTabTableColumnParams(prop));
    },
    //
    async useRowRemove(prop, scope) {
      const { REMOVE } = TABLE;
      const {
        $index,
        row: { id, contractId },
      } = scope;
      if (id) {
        try {
          // try
          this.loading = true;
          this.loadingText = "删除子表中";
          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) {
          this.loadingText = "更新子表中";
          await EDIT(row, prop);
        } else {
          this.loadingText = "新增信息中";
          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;
            this.loadingText = "更新合同中";
            const {
              params,
              params: { status },
            } = this;
            const TASK = status === "3" ? ALTERATION : EDIT;
            const { msg, code } = await TASK(params);
            if (code === 200) {
              this.hide();
              this.$emit("submit-success");
              this.$notify.success(msg);
            }
          } catch (err) {
            // catch
            console.error(err);
          } finally {
            // finally
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
  },
  created() {
    this.open();
  },
  mounted() {},
  destroyed() {},
};
</script>
<template>
  <div
    v-loading="loading"
    :element-loading-text="loadingText"
    style="height: 100vh; display: flex; flex-direction: column"
  >
    <div
      style="
        height: 50px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 18px;
      "
    >
      <h4 class="m-0" style="font-weight: 500; flex: 1">{{ title }}</h4>
      <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 v-if="params.code" style="flex: 1; overflow-y: auto">
      <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"
      >
        <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>
    </div>
    <el-tabs v-if="params.code" 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="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>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
