<script>
import { GENERATE } from "@/api/business/purchase/task";
import useColumns from "./columns";
import { dicts } from "../dicts";

export default {
  name: "PiGai",
  props: {
    selectData: {
      type: Array,
      require: true,
    },
  },
  dicts: dicts,
  components: {
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
    ElPopoverMultipleSelectV2: () =>
      import("@/components/popover-select-v2/multiple.vue"),
    ElPopoverTreeSelect: () =>
      import("@/components/popover-tree-select/index.vue"),
    ElPopoverMultipleTreeSelect: () =>
      import("@/components/popover-tree-select/multiple.vue"),
    ElDateWrapper: () => import("@/components/date-wrapper/index.vue"),
  },
  data() {
    let { TableColumns, SelectColumns } = useColumns();
    return {
      title: "批改",
      visible: false,
      TableColumns: TableColumns,
      SelectColumns: SelectColumns,
      innerValue: [],
    };
  },
  computed: {
    disabled: {
      get() {
        let { selectData } = this.$props;
        if (selectData.length > 0) {
          // 0-自由态；3-已回退
          const STATUS = ["0", "3"];
          let notList = selectData.filter(
            (item) => STATUS.findIndex((s) => s == item.status) === -1
          );
          return notList.length > 0;
        }
        return true;
      },
      set() {},
    },
  },
  watch: {},
  methods: {
    onClick() {
      this.visible = true;
    },
    async onSave() {
      try {
        this.$modal.loading("处理中......");

        let puOrderGenerateList = JSON.parse(
          JSON.stringify(this.innerValue)
        ).map((item) => {
          if (item.attr.is === "el-popover-select-v2") {
            for (const key in item.attr.dataMapping) {
              item[key] = item[key] || "~";
            }
          } else {
            item[item.candidate] = item["value"] === "" ? "~" : item["value"];
          }
          return item;
        });

        let ids = this.$props.selectData.map((item) => item.id);

        console.log({ puOrderGenerateList, ids }, "puOrderGenerateList");

        let { code, msg } = await GENERATE({
          ids,
          puOrderGenerateList,
        });

        if (code === 200) {
          this.$notify.success({ message: msg });
          this.$emit("success");
          this.onCancel();
        }
      } catch (error) {
      } finally {
        this.$modal.closeLoading();
      }
    },
    onCancel() {
      this.visible = false;
      let { TableColumns, SelectColumns } = useColumns();
      this.TableColumns = TableColumns;
      this.SelectColumns = SelectColumns;
      this.innerValue = [];
    },
    onRowAdd() {
      this.innerValue.push({
        ...this.$init.params([...this.TableColumns]),
        attr: {
          is: "el-input",
        },
      });
    },
    canidateChange(prop) {
      let { $index, row } = prop;
      this.judgeDisabled();

      let selectValue = this.SelectColumns.filter(
        ({ item }) => item.key === row.candidate
      )[0];

      let attr = selectValue.attr ? selectValue.attr : { is: "el-input" };

      this.innerValue = this.innerValue.map((tableItem, index) => {
        if (row.candidate === tableItem.candidate && $index === index) {
          tableItem.attr = attr;
          tableItem.value = "";
        }

        return tableItem;
      });
    },
    judgeDisabled(prop) {
      // 重置
      this.SelectColumns = this.SelectColumns.map(({ item, attr }) => {
        item.disabled = false;

        let index = this.innerValue.findIndex(
          (inVal) => inVal.candidate === item.key
        );
        // 存在
        if (index !== -1) {
          item.disabled = true;
        }

        return {
          item,
          attr,
        };
      });
    },
    onRowRemove(prop) {
      const { $index, row } = prop;
      this.innerValue.splice($index, 1);
      this.judgeDisabled();
    },
  },
  created() {},
};
</script>

<template>
  <el-button :size="$attrs.size" :disabled="disabled" @click="onClick"
    >{{ title }}
    <el-dialog
      :show-close="false"
      :visible.sync="visible"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div slot="title" style="display: flex; justify-content: space-between">
        <h4 style="margin: 0">{{ title }}</h4>
        <div>
          <el-button :size="$attrs.size" type="primary" @click="onSave"
            >确认</el-button
          >
          <el-button :size="$attrs.size" @click="onCancel">取消</el-button>
        </div>
      </div>

      <el-row style="display: flex; align-items: center; margin-bottom: 6px">
        <el-col :span="12">
          <span style="color: #ff4e4e; display: inline-block">*</span>
          批改范围：仅选中内容
        </el-col>
        <el-col style="padding-left: 10px">
          <el-button type="text" @click.native.prevent="onRowAdd">
            <i class="el-icon-plus"></i>
            新增修改项
          </el-button>
        </el-col>
      </el-row>

      <el-table
        :data="innerValue"
        style="width: 100%"
        :show-header="false"
        :height="320"
        empty-text=" "
        v-bind="$attrs"
        v-on="$listeners"
      >
        <el-table-column
          v-for="({ item, attr }, index) in TableColumns"
          :key="item.key + index"
          :prop="item.key"
          :label="item.title"
          :fixed="item.fixed"
          :width="item.width || 200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-select
              v-if="item.key === 'candidate'"
              v-model="scope.row[item.key]"
              :size="$attrs.size"
              placeholder="请选择"
              @change="canidateChange(scope)"
            >
              <el-option
                v-for="(c, index) in SelectColumns"
                :key="index + c.item.key"
                :label="c.item.title"
                :value="c.item.key"
                :disabled="c.item.disabled"
              ></el-option>
            </el-select>

            <template v-if="item.key === 'value'">
              <component
                v-if="scope.row.attr.is === 'el-select'"
                v-bind="scope.row.attr"
                :size="$attrs.size"
                v-model="scope.row[item.key]"
              >
                <template>
                  <el-option
                    v-for="d in dict.type[scope.row.attr.dictName]"
                    :key="d.value"
                    :label="d.label"
                    :value="d.value"
                  >
                  </el-option>
                </template>
              </component>

              <component
                v-if="scope.row.attr.is === 'el-popover-select-v2'"
                v-bind="scope.row.attr"
                v-model="scope.row[item.key]"
                :title="item.title"
                :size="$attrs.size"
                :source.sync="scope.row"
                style="width: 100%"
              ></component>

              <component
                v-if="scope.row.attr.is === 'el-popover-multiple-select-v2'"
                v-bind="scope.row.attr"
                v-model="scope.row[item.key]"
                :title="item.title"
                :size="$attrs.size"
                :source.sync="scope.row"
                style="width: 100%"
              ></component>

              <component
                v-if="scope.row.attr.is === 'el-popover-tree-select'"
                v-bind="scope.row.attr"
                v-model="scope.row[item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                @change="$emit('submit')"
                style="width: 100%"
              >
              </component>

              <component
                v-if="scope.row.attr.is === 'el-popover-multiple-tree-select'"
                v-bind="scope.row.attr"
                v-model="scope.row[item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                style="width: 100%"
              >
              </component>

              <component
                v-if="scope.row.attr.is === 'el-date-wrapper'"
                v-bind="scope.row.attr"
                v-model="scope.row[item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                style="width: 100%"
              >
              </component>

              <component
                v-if="scope.row.attr.is === 'el-input'"
                v-bind="scope.row.attr"
                :size="$attrs.size"
                v-model="scope.row[item.key]"
                style="width: 100%"
              >
              </component>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="50">
          <template slot-scope="scope">
            <i
              class="el-icon-delete"
              @click.prevent="onRowRemove(scope)"
              style="cursor: pointer"
            ></i>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </el-button>
</template>

<style scoped>
/deep/.el-dialog__body {
  padding: 0px 20px 20px;
}
</style>

<style lang="scss" scoped>
::v-deep.el-table::before {
  display: none;
}

::v-deep.el-table {
  th,
  td,
  th.is-leaf {
    border: none;
  }

  .el-table__cell {
    padding: 2px 0;
  }
  .popover-select-v2 .popover-select-v2_tags,
  .popover-tree-select .popover-tree-select_tags {
    left: 15px;
  }
  .el-scrollbar__view {
    padding: 6px 0 0 3px !important;
  }

  .el-scrollbar__wrap {
    overflow-x: hidden;
    margin-right: -2px !important;
  }
}
</style>
