<script>
import useColumns from "./column";
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,
    },
  },
  components: {
    ElFileUpload: () => import("@/components/FileUpload/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
    ElComputedInputV2: () => import("@/components/computed-input-v2/index.vue"),
  },
  data() {
    const {
      TabColumns,
      FormColumns,
      TabColumns: [
        {
          item: { key: tabName },
        },
      ],
    } = useColumns();
    const params = initParams([...TabColumns, ...FormColumns]);
    const rules = initRules(FormColumns);
    return {
      title: "编 辑",
      width: "100%",
      visible: false,
      loading: false,
      rules: rules,
      params: params,
      tabName: tabName,
      TabColumns,
      FormColumns,
    };
  },
  computed: {
    $dicts: {
      get() {
        return this.$parent.$parent.$parent.dict.type;
      },
      set() {},
    },
    disabled: {
      get() {
        return this.selectData.length !== 1;
      },
      set() {},
    },
  },
  watch: {},
  methods: {
    async fetchRefer(row, prop) {
      const { rateCode } = row;
      const { source, referName } = prop;
      if (referName === "MATERIAL_PARAM") {
        try {
          // try
          this.loading = true;
          const { code, rows } = await REFER({
            search: rateCode,
            type: "TAX_RATE_PARAM",
          });
          if (code === 200) {
            const [{ ntaxrate }] = rows;
            source.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(prop) {
      this.visible = await this.fetchItem(prop);
    },
    //
    async hide() {
      const {
        TabColumns,
        FormColumns,
        TabColumns: [
          {
            item: { key: tabName },
          },
        ],
      } = useColumns();
      this.visible = false;
      this.tabName = tabName;
      this.params = initParams([...TabColumns, ...FormColumns]);
    },
    //
    async useRowAdd(prop) {
      const { TableColumns } = this.TabColumns.find(
        ({ item: { key } }) => key === prop
      );
      this.params[prop].push(initParams(TableColumns));
      console.log(this.params[prop]);
    },
    //
    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(selectData[0].id)"
  >
    {{ title }}
    <el-drawer
      :size="width"
      :title="title"
      :visible.sync="visible"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="ruleForm"
        v-loading="loading"
        :size="$attrs.size"
        :rules="rules"
        :model="params"
        label-width="auto"
        label-position="right"
        style="padding: 10px"
      >
        <el-row :gutter="20" style="display: flex; flex-wrap: wrap">
          <el-col
            v-for="{ item, attr } in FormColumns"
            :key="item.key"
            :span="item.span || 6"
          >
            <el-form-item :prop="item.key" :label="item.title">
              <component
                v-if="attr.is === 'el-input'"
                v-bind="attr"
                v-model="params[item.key]"
                style="width: 100%"
              ></component>
              <component
                v-if="attr.is === 'el-popover-select-v2'"
                v-bind="attr"
                v-model="params[item.key]"
                :source.sync="params"
                style="width: 100%"
              >
              </component>
              <component
                v-if="attr.is === 'el-input-number'"
                v-bind="attr"
                v-model="params[item.key]"
                style="width: 100%"
              ></component>
              <component
                v-if="attr.is === 'el-select'"
                v-bind="attr"
                v-model="params[item.key]"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in $dicts[attr.dictName]"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </component>
              <component
                v-if="attr.is === 'el-date-picker'"
                v-bind="attr"
                v-model="params[item.key]"
                style="width: 100%"
              >
              </component>
              <component
                v-if="attr.is === 'el-file-upload'"
                v-bind="attr"
                v-model="params[item.key]"
              ></component>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="0">
              <el-tabs v-model="tabName">
                <el-tab-pane
                  v-for="{ item, attr, TableColumns } in TabColumns"
                  :key="item.key"
                  :label="item.title"
                  :name="item.key"
                  lazy
                >
                  <el-table :size="$attrs.size" :data="params[item.key]">
                    <el-table-column label="序号">
                      <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      v-for="{ item: cItem, attr: cAttr } in TableColumns"
                      :key="cItem.key"
                      :prop="cItem.key"
                      :label="cItem.title"
                      :width="cItem.width || 300"
                      show-overflow-tooltip
                    >
                      <template slot-scope="scope">
                        <component
                          v-if="cAttr.is === 'el-input'"
                          v-bind="cAttr"
                          v-model="scope.row[cItem.key]"
                          style="width: 100%"
                        ></component>
                        <component
                          v-else-if="cAttr.is === 'el-popover-select-v2'"
                          v-bind="cAttr"
                          v-model="scope.row[cItem.key]"
                          :source.sync="scope.row"
                          style="width: 100%"
                          @change="fetchRefer"
                        >
                        </component>
                        <component
                          v-else-if="cAttr.is === 'el-input-number'"
                          v-bind="cAttr"
                          v-model="scope.row[cItem.key]"
                          style="width: 100%"
                        ></component>
                        <component
                          v-else-if="cAttr.is === 'el-select'"
                          v-bind="cAttr"
                          v-model="scope.row[cItem.key]"
                          style="width: 100%"
                        >
                          <el-option
                            v-for="dict in $dicts[cAttr.dictName]"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          >
                          </el-option>
                        </component>
                        <component
                          v-else-if="cAttr.is === 'el-date-picker'"
                          v-bind="cAttr"
                          v-model="scope.row[cItem.key]"
                          style="width: 100%"
                        >
                        </component>
                        <component
                          v-else-if="cAttr.is === 'el-computed-input-v2'"
                          v-bind="cAttr"
                          v-model="scope.row[cItem.key]"
                          :source.sync="scope.row"
                        ></component>
                        <span v-else> {{ scope.row[cItem.key] }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                      <template slot="header" slot-scope="scope">
                        <el-button
                          circle
                          icon="el-icon-plus"
                          :size="$attrs.size"
                          @click="useRowAdd(tabName)"
                        >
                        </el-button>
                      </template>
                      <template slot-scope="scope">
                        <el-button
                          circle
                          icon="el-icon-check"
                          :size="$attrs.size"
                          @click.native.prevent="useRowSubmit(tabName, scope)"
                        >
                        </el-button>
                        <el-button
                          circle
                          icon="el-icon-minus"
                          :size="$attrs.size"
                          @click.native.prevent="useRowRemove(tabName, scope)"
                        >
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="padding: 20px; text-align: right">
        <el-button :size="$attrs.size" :loading="loading" @click="hide"
          >取 消</el-button
        >
        <el-button
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="useSubmit('ruleForm')"
          >确 认</el-button
        >
      </div>
    </el-drawer>
  </el-button>
</template>
