<template>
  <div class="parameter pagePadding">
    <div
      v-loading="loading"
      v-if=" powers.some((i) => i == '001')"
    >
      <el-input
        style="width: 100%; margin: 15px 0 0 0"
        type="textarea"
        v-model="desc"
        placeholder="请接入扫码枪，识别票二维码！"
        @input="input_change"
        @blur="blur_change"
      ></el-input>
      <!-- <div v-for="(si, sii) in this.tableData" :key="si + sii">{{ si }}</div> -->
      <div>
        <el-table
          :data="tableData"
          style="width: 100%; margin: 20px 0 0 0"
          :size="'mini'"
          border
          stripe
        >
          <el-table-column
            type="index"
            label="顺序"
            show-overflow-tooltip
            width="60px"
          />
          <el-table-column
            prop="value0"
            label="发票类型"
            show-overflow-tooltip
            min-width="100px"
          />
          <!-- <el-table-column prop="value1" label="日期" show-overflow-tooltip  min-width="100px"/> -->
          <el-table-column
            prop="value2"
            label="发票代码"
            show-overflow-tooltip
            min-width="100px"
          />
          <el-table-column
            prop="value3"
            label="发票号码"
            show-overflow-tooltip
            min-width="100px"
          />
          <el-table-column
            prop="value4"
            label="金额（不含税）"
            show-overflow-tooltip
            min-width="100px"
          />
          <el-table-column
            prop="value5"
            label="开票日期"
            show-overflow-tooltip
            min-width="100px"
          />
          <el-table-column
            prop="value6"
            label="检验码"
            show-overflow-tooltip
            min-width="100px"
          />
          <!-- <el-table-column
            prop="value7"
            label="日期"
            show-overflow-tooltip
            min-width="100px"
          /> -->
        </el-table>
      </div>
    </div>
    <no-auth v-else></no-auth>
    <!-- 弹窗 新增/修改 -->
    <add-edit
      :id="modelId"
      :show-model="showModel"
      :sitem="sitem"
      @refresh="searchList"
      @cancel="showModel = false"
    />
  </div>
</template>
<script>
import addEdit from "./addEdit";
import asyncRequest from "@/apis/service/serviceParam/parameter";
import { statusList } from "@/assets/js/statusList";
import roleLevel from "@/assets/js/roleLevel";
import mixinPage from "@/mixins/elPaginationHandle";
import { mapGetters } from "vuex";
import resToken from "@/mixins/resToken";
export default {
  name: "parameter",
  mixins: [mixinPage, resToken],
  components: {
    addEdit,
  },
  computed: {
    //组件SIZE设置
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "parameter"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      desc: "",
      statusList: statusList,
      roleLevel: roleLevel,
      loading: false,
      showModel: false,
      modelId: "000",
      sitem: {},
      parmValue: {
        page: 1, // 页码
        size: 15, // 每页显示条数
        start: "",
        end: "",
        status: "",
        creater: "",
      },
      // 状态
      statusOptions: [
        { id: "0", label: "禁用" },
        { id: "1", label: "启用" },
      ],
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"],
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      // 表格 - 列参数
      columns: [
        {
          prop: "id",
          label: "ID",
        },
        {
          prop: "parameter_name",
          label: "系统参数名称",
        },
        {
          prop: "status",
          label: "状态",
          sortable: true,
          _slot_: "status",
        },
        {
          prop: "creater",
          label: "创建人",
        },
        {
          prop: "addtime",
          label: "创建时间",
          sortable: true,
        },
        {
          prop: "",
          label: "操作",
          fixed: "right",
          _noset_: true,
          _slot_: "operation",
        },
      ],
    };
  },
  mounted() {
    // this.searchList();
  },
  methods: {
    input_change() {
      if ((this.desc ?? "") && this.desc.indexOf("\n") !== -1) {
        this.textarea_change();
      }
    },
    blur_change() {
      if (this.desc ?? "") {
        this.textarea_change();
      }
    },
    textarea_change() {
      let i = this.desc.indexOf("，");
      if (i !== -1) {
        this.$message.warning("请将输入法切换至英文！");
        setTimeout(() => {
          this.desc = "";
        }, 1500);
      }
      console.log(this.desc);
      let a = this.desc.split(",");
      if (a.length >= 8) {
        let model = {};
        for (let i = 0; i < 8; i++) {
          model[`value${i}`] = a[i];
        }
        if (this.tableData.length === 0) {
          this.tableData.push(model);
        } else if (!this.is_repeat(model)) {
          this.tableData.push(model);
        } else {
          this.$message.warning("重复扫描！");
        }
        this.desc = "";
      }
      console.log(this.tableData);
    },
    is_repeat(model) {
      let is = false;
      this.tableData.forEach((e) => {
        let modela = JSON.parse(JSON.stringify(e));
        let modelb = JSON.parse(JSON.stringify(model));
        let isok = this.isObjectChanged(modela, modelb);
        if (isok) {
          is = isok;
        }
      });
      return is;
    },
    isObjectChanged(source, comparison) {
      const _source = JSON.stringify(source);
      const _comparison = JSON.stringify(comparison);
      return _source === _comparison;
    },

    restSearch() {
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.parmValue = {
        page: 1, // 页码
        size: 15, // 每页显示条数
        start: "",
        end: "",
        status: "",
        creater: "",
      };
      this.searchList();
    },
    // 新建/编辑/详情
    openModal(row, type) {
      this.sitem = row;
      this.modelId = type;
      this.showModel = true;
    },
    // 时间
    async handleTime(e) {
      this.parmValue.start = e.startTime || "";
      this.parmValue.end = e.endTime || "";
      if (
        (this.parmValue.start !== "" && this.parmValue.end !== "") ||
        (this.parmValue.start === "" && this.parmValue.end === "")
      ) {
        this.pageInfo.curr = 1;
        this.parmValue.page = 1;
        await this.searchList();
      }
    },
    /**
     * 启用/禁用
     * @param {String} id id
     * @param {String} status 0-禁用 1-启用
     */
    async changeStatus(id, status) {
      await this.$confirm(`确定要改为${status === "1" ? "禁用" : "启用"}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.loading = true;
          const model = {
            id: id,
            status: status === "1" ? "0" : "1",
          };
          const res = await asyncRequest.status(model);
          if (res && res.code === 0) {
            this.loading = false;
            this.$notify.success({
              title: "状态修改成功！",
              message: "",
            });
            await this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.loading = false;
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    async deleteItem(id) {
      await this.$confirm("确定要删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            id: id,
          };
          const res = await asyncRequest.delete(model);
          if (res && res.code === 0) {
            this.$notify.success({
              title: "删除成功",
              message: "",
            });
            this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    // 刷新表格
    async searchList() {
      if (
        (this.parmValue.start !== "" && this.parmValue.end === "") ||
        (this.parmValue.start == "" && this.parmValue.end != "")
      ) {
        this.$message.warning("开始时间和结束时间不能为空");
        return;
      }
      this.loading = true;
      const res = await asyncRequest.list(this.parmValue);
      if (res && res.code === 0 && res.data) {
        this.tableData = res.data.list;
        this.pageInfo.total = Number(res.data.count);
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
