<template>
	<div>
		<el-card class="box-card" :class="[isShowCard ? '' : 'is-show-card']">
			<c-col :span="24">
				<el-form-item :label="argadr.title" :prop="`recgrp.rec.${argadr.extkey}`" style="width: 100%" :rules="[
              {required: requiredExtkey, message: '必输项', trigger:['blur','change'] }
            ]">
					<c-input v-model.trim="model.recgrp.rec[argadr.extkey]" placeholder="" maxlength="16" :disabled="disabledExtkey" :customModifykey="`recgrp.rec.${argadr.extkey}`" clearable @keyup.enter.native="showPtapDialog()" @blur="handleExtkeyBlur" @clear="clear" @input="extkeyInput">
					</c-input>
				</el-form-item>
			</c-col>
			<c-col :span="24">
				<el-form-item :label="argadr.namLabel" :prop="`recgrp.rec.${argadr.nam}`">
					<c-mul-row-input type="textarea" :rows="2" :cols="70" :autosize="{minRows: 1,	maxRows: 2}" :charmod="charmod" :showTip="false" :isRequired="requiredNam" :customModifykey="`recgrp.rec.${argadr.nam}`" v-model="model.recgrp.rec[argadr.nam]" placeholder="" :disabled="disabledNamelc || isDisabled">
					</c-mul-row-input>
				</el-form-item>
			</c-col>
			<c-col :span="24">
				<el-form-item :label="argadr.codeLabel" :prop="`recgrp.rec.${argadr.custcode}`" style="width: 100%">
					<c-input v-model.trim="model.recgrp.rec[argadr.custcode]" placeholder="" :disabled="isDisabled" :customModifykey="`recgrp.rec.${argadr.custcode}`">
					</c-input>
				</el-form-item>
			</c-col>
		</el-card>
		<!-- 弹窗 -->
		<el-dialog v-dialogDrag width="64%" :visible.sync="dialogTableVisible" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" v-if="dialogTableVisible" :modal-append-to-body="false" :append-to-body="true">
			<div slot="title" style="font-size: 16px;color: black;position: realtive;">
				{{ dialogTitle }}
				<!-- 关闭按钮 -->
				<div class="close-btn" @click="handleCloseDialogTable">
					<i class="el-icon-close"></i>
				</div>
			</div>
			<div v-if="!tableLoading && tableList.length === 0">暂无数据</div>
			<div v-else style="width: 100%;height: 100%;">
				<el-table id='tableRef' height="calc(100% - 32px)" style="width: 100%;" v-loading="tableLoading" :data="tableList" @row-dblclick="dbClickRow" :before-close="beforeClose">
					<el-table-column v-for="(item,key) in tableColumn" :key="key" :prop="item.prop" :render-header="renderheader" :label="item.label">
					</el-table-column>
				</el-table>
				<el-pagination class="eContainer-pagination" layout="prev, pager, next, jumper, ->, sizes, total" :page-sizes="pageSizes" :page-size="pageSize" :current-page="currentPage" :total="total" @size-change="sizeChange" @current-change="currentChange"></el-pagination>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import { columnMap } from "./ptapColumn.js";
import { queryPtyInfos } from "~/service/business/common";
import commonFunctions from "~/mixin/commonFunctions.js";
import commonDepend from "~/mixin/commonDepend.js";
export default {
  inject: ["root"],
  mixins: [commonFunctions, commonDepend],
  props: {
    model: {
      type: Object,
      default: () => {}
    },
    argadr: {
      type: Object,
      default: function() {
        return {
          title: "", //角色名称
          nam: "",
          extkey: "",
          custcode: "",
          codeLabel: "",
          namLabel: ""
        };
      }
    },
    isShowNam: {
      type: Boolean,
      default: true
    },
    charmod: {
      type: Number,
      default: 0
    },
    isShowCard: {
      type: Boolean,
      default: false
    },
    // extkey必填星号*是否显示
    requiredExtkey: {
      type: Boolean,
      default: false
    },
    ptytyp: {
      // 决定弹框的表头--客户类型
      type: String,
      default: "C"
    },
    // 名称必填星号*是否显示
    requiredNam: {
      type: Boolean,
      default: false
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    disabledExtkey: {
      //extkey是否灰显(true:extkey处灰显)
      type: Boolean,
      default: false
    },
    disabledNamelc: {
      //namelc是否灰显(true:namelc处灰显)
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogTitle: "", // 弹框标题
      dialogTableVisible: false, // 控制弹框的展示和隐藏
      tableLoading: false,
      total: 0,
      currentPage: 1, // 页数
      pageSizes: [5, 10, 20, 30, 40, 50, 100],
      pageSize: 5, // 条数
      tableList: [],
      tableColumn: [],
      markExtkey: ""
    };
  },
  methods: {
    // 弹框
    async showPtapDialog() {
      if (this.tableLoading || this.dialogTableVisible) {
        return;
      }
      const value = this.model.recgrp.rec[this.argadr.extkey];
      // 分层取值
      await this.getTableData(value);
      if (this.total == 1) {
        this.dbClickRow(this.tableList[0]);
      } else {
        // 设置弹框标题
        this.dialogTitle = `${this.argadr.title}详情`;
        this.dialogTableVisible = true;
        this.tableColumn = columnMap["Y"];
        this.$nextTick(() => {
          this.root.$refs["modelForm"].validateField([
            `recgrp.rec.${this.argadr.extkey}`
          ]);
        });
      }
    },
    //extkey清空时
    extkeyInput() {
      if (!this.model.recgrp.rec[this.argadr.extkey]) {
        this.model.recgrp.rec[this.argadr.nam] = "";
        this.model.recgrp.rec[this.argadr.custcode] = "";
        this.markExtkey = "";
        this.clear();
      }
    },
    // 清除
    clear() {
      this.$emit("clear");
      this.$nextTick(() => {
        this.root.$refs["modelForm"].validateField([
          `recgrp.rec.${this.argadr.extkey}`
        ]);
      });
    },
    // 关闭弹框
    handleCloseDialogTable() {
      this.dialogTableVisible = false;
    },
    async dbClickRow(row, column, event) {
      this.markExtkey = row.extkey;
      this.model.recgrp.rec[this.argadr.extkey] = row.extkey;
      this.model.recgrp.rec[this.argadr.nam] = row.nam;
      this.model.recgrp.rec[this.argadr.custcode] = row.juscod;
      this.$nextTick(() => {
        this.root.$refs["modelForm"].validateField([
          `recgrp.rec.${this.argadr.extkey}`
        ]);
      });
      this.dialogTableVisible = false;
    },
    beforeClose(done) {
      this.dialogTableVisible = false;
      this.currentPage = 1;
      done();
    },
    // 表头 头部换行,以 / 作为换行标志
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("/")[0]),
        h("br"),
        h("span", {}, column.label.split("/")[1])
      ]);
    },
    // extkey输入框失焦
    handleExtkeyBlur(e) {
      let extkey = this.model.recgrp.rec[this.argadr.extkey];
      if (extkey && extkey !== this.markExtkey) {
        this.showPtapDialog();
      }
    },
    sizeChange(num) {
      this.pageSize = num;
      const value = this.model.recgrp.rec[this.argadr.extkey];
      this.getTableData(value);
    },
    currentChange(num) {
      this.currentPage = num;
      const value = this.model.recgrp.rec[this.argadr.extkey];
      this.getTableData(value);
    },
    // 获取弹框内的table数据
    async getTableData(value) {
      return new Promise(async resolve => {
        this.tableLoading = true;
        this.tableList = [];
        // 获取table的表格数据
        let params = {
          extkey: value || "",
          bchbranch: JSON.parse(window.sessionStorage.accbch).branch,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        };
        const loading = this.loading();
        const res = await queryPtyInfos(params, this.moduleRouter());
        loading.close();
        if (res.respCode == SUCCESS) {
          if (res.data && res.data.list) {
            this.total = res.data.total;
            this.tableList = res.data.list;
            resolve(this.tableList);
          }
        }
        this.tableLoading = false; //接口掉完变成false
      });
    }
  }
};
</script>
<style scoped lang="less">
.box-card {
  margin-bottom: 10px;
  /deep/ .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 10px;
  }
  /deep/ .el-card__body {
    padding: 10px 10px 10px 0px;
  }
}
.close-btn {
  width: 20px;
  height: 20px;
  position: absolute;
  top: 20px;
  right: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
.close-btn:hover {
  background: rgba(0, 0, 0, 0.1);
}
.is-show-card {
  border: none !important;
  box-shadow: none !important;
  margin-bottom: 0 !important;
  /deep/ .el-card__body {
    padding: 0 !important;
  }
}
</style>