<template>
	<div class="clearfix">
		<c-col :span="24" style="margin-bottom: 18px">
			<c-table :border="border" :highlight-current-row="highlight" :list="model" :paginationShow="paginationShow" :row-class-name="tableRowClassName" @row-click="handleClick" style="text-align: center">
				<el-table-column type="index" v-if="isIndex" width="50">
				</el-table-column>
				<template v-for="item in columns">
					<el-table-column :key="item.dataIndex" :label="item.title" :min-width="item.width">
						<template slot-scope="scope">
							<c-select
							  :isFixed="true"
								v-if="item.show === 'select'"
								:disabled="disabledAll"
								@change="handleChangeRole(scope.row, scope.$index, item.dataIndex)"
								v-model="scope.row[item.dataIndex]"
							>
								<el-option
									v-for="item in roleList"
									:key="item.value"
									:value="item.value"
									:label="item.label"
								></el-option>
							</c-select>
							<div style="display: flex;justify-content: flex-start;" v-else-if="item.show === 'input'">
								<c-input :disabled="disabledAll" :placeholder="`请输入${item.title}`" @keyup.enter.native="showPtapDialog(scope.row, scope.$index, item.dataIndex)" v-model="scope.row[item.dataIndex]"></c-input>
								<c-button @click="showPtapDialog(scope.row, scope.$index, item.dataIndex)" icon="el-icon-info" size="small" style="margin:0 0" type="primary"></c-button>
							</div>
							<c-checkbox :disabled="disabledAll" :placeholder="`请输入${item.title}`" checked v-else-if="item.show === 'checkbox'" v-model="scope.row[item.dataIndex]"></c-checkbox>
							<span v-else>{{ scope.row[item.dataIndex] }}</span>
						</template>
					</el-table-column>
				</template>
				<el-table-column :offset="1" :span="1" fixed="right" label="" prop="det" v-if="isShowOperation" width="150px">
					<template slot="header" slot-scope="scope">
						<c-button @click="handleAdd(scope)" circle class="el-icon-plus" size="mini" style="padding: 4px">
						</c-button>
						<c-button @click="handleDelete(scope)" circle class="el-icon-minus" size="mini" style="padding: 4px">
						</c-button>
					</template>
					<!-- 可以用自定义方式添加操作 -->
					<slot>
						<!-- 详情 -->
						<template slot-scope="scope">
							<el-button @click="handleDetails(scope.row)" icon="el-icon-info" size="mini" type="primary"></el-button>
						</template>
					</slot>
				</el-table-column>
			</c-table>
		</c-col>
		<!-- 弹窗 -->
		<el-dialog v-dialogDrag :title="dialogTitle" :visible.sync="dialogTableVisible" v-if="dialogTableVisible" width="80%">
			<div v-if="!loading && tableList.length === 0">暂无数据</div>
			<div style="width: 100%;height: 100%;" v-else>
				<el-table :before-close="beforeClose" :data="tableList" @row-dblclick="dbClickRow" height="calc(100% - 32px)" id='tableRef' style="width: 100%;" v-loading="loading">
					<el-table-column :key="key" :label="item.label" :prop="item.prop" :render-header="renderheader" v-for="(item,key) in tableColumn">
					</el-table-column>
				</el-table>
				<el-pagination :current-page="currentPage" :page-size="pageSize" :total="total" @current-change="currentChange" layout="prev, pager, next, jumper">
				</el-pagination>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import Table from "./Table.vue";
import { columnMap } from "./Ptap/ptapColumn.js";
import { getPtaTableDtat, getPtsptaByInr } from "~/service/business/common";
import Utils from "~/utils";

export default {
  components: { "c-table": Table },
  inject: ["root"],
  data() {
    return {
      rowIndex: null,
      dialogTitle: "", // 弹框标题
      dialogTableVisible: false, // 控制弹框的展示和隐藏
      loading: true,
      total: 0,
      currentPage: 1,
      pageSizes: [5, 10, 20, 30, 40, 50, 100],
      pageSize: 5,
      columns: [
        {
          title: "角色",
          width: "120px",
          dataIndex: "rol",
          show: "select"
        },
        {
          title: "当事人",
          width: "210px",
          dataIndex: "extkey",
          show: "input"
        },
        {
          title: "当事人名称",
          width: "250px",
          dataIndex: "nam"
        },
        {
          title: "地址编号",
          width: "250px",
          dataIndex: "ref"
        }
      ],
      tableList: [],
      inputValue: "",
      tableColumn: [],
      currentRowIndex: 0,
      currentRowData: {}
    };
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    roleList: {
      type: Array,
      default: () => []
    },
    paginationShow: {
      type: Boolean,
      default: false
    },
    disabledAll: {
      //是否全部灰显
      type: Boolean,
      default: false
    },

    border: {
      //是否有边框
      type: Boolean,
      default: true
    },
    highlight: {
      type: Boolean,
      default: true
    },
    isIndex: {
      type: Boolean,
      default: false
    },
    // 是否显示操作列
    isShowOperation: {
      type: Boolean,
      default: true
    },
    // ptytyp: {
    //   //决定弹框的表头
    //   type: String,
    //   default: "C"
    // },
    bchinr: {
      type: String,
      default: "00000047"
    },
    keyCode: {
      type: String,
      default: "gidgrp"
    }
  },
  computed: {
    model: {
      get() {
        return this.value;
      },
      set(newVal) {
        console.log(newVal);
        this.$emit("input", newVal);
      }
    }
  },
  methods: {
    // 改变角色
    handleChangeRole(row, index, key) {
      if (key === "rol") {
        this.currentRowIndex = index;
        this.currentRowData = row;
        // 回填角色数据
        this.setRoleData();
      }
    },
    // 回填角色中的pts
    setRoleData() {
      if (this.currentRowData.rol && this.root) {
        let rol = this.currentRowData.rol.toLowerCase();
        let rootRolData = this.root.model[this.keyCode][rol];
        if (rootRolData) {
          if (Utils.typeOf(rootRolData.pts) === "Object") {
            this.root.model[this.keyCode][rol].pts = {
              ...rootRolData.pts,
              ...this.model[this.currentRowIndex]
            };
          }
        } else {
          this.$set(this.root.model[this.keyCode], rol, {
            pts: {
              ...this.model[this.currentRowIndex]
            }
          });
        }
      }
    },
    showPtapDialog(row, index, key) {
			// const selectPtytyp=row.rol
    	// if( selectPtytyp==="DRW"|| selectPtytyp==="BE2" || selectPtytyp==="OAP" ){
			// 	this.ptytyp="C"
		  // }else{
			// 	this.ptytyp="B"
			// }
      this.roleList.forEach(item=>{
        if(item.value===row.rol){
					this.ptytyp=item.ptytyp
				}
			})
      this.currentRowIndex = index;
      this.currentRowData = row;
      const value = this.model[index][key];
      // 设置弹框标题
      this.dialogTitle = `当事人详情`;
      this.dialogTableVisible = true;
      this.tableColumn = columnMap["C"];
      // 分层取值
      this.getTableData(value,this.ptytyp);
    },
    // 表头 头部换行,以 / 作为换行标志
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("/")[0]),
        h("br"),
        h("span", {}, column.label.split("/")[1])
      ]);
    },
    // 获取弹框内的table数据
    getTableData(value) {
      this.loading = true;
      this.tableList = [];
      this.currentPage = 1;
      this.pageSize = 10;
      this.total = 0;
      // 获取table的表格数据
      let params = {
        ptytyp: this.ptytyp,
        extkey: value || "",
        bchinr: this.bchinr,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      getPtaTableDtat(params, this.moduleRouter()).then(res => {
        if (res.respCode === SUCCESS) {
          if (res.data && res.data.list) {
            this.total = res.data.total;
            this.tableList = res.data.list.map(it => ({
              ...it,
              // 添加新key将Party Number和Address Number换行
              partyNumberAndAdressNumber: `${it.ptaptyextkey}\n${it.ptaobjkey}`,
              bchbranchAndBchbchname: `${it.bchbranch}\n${it.bchbchname}`,
              adrnam1AndPtanam1: `${it.adrnam1}\n${it.ptanam1}`,
              adradr1AndAdrstr1: `${it.adradr1}\n${it.adrstr1}`,
              adrstr2Andadrloccty: `${it.adrstr2}\n${it.adrloccty}`,
              adrloczipAndadrloctxt: `${it.adrloczip}\n${it.adrloctxt}`
            }));
            this.currentPage = res.data.offset;
            this.pageSize = res.data.limit;
          }
        }
        this.loading = false; //接口掉完变成false
      });
    },
    async dbClickRow(row, column, event) {
      let params = {
        inr: row.ptainr
      };
      const response = await getPtsptaByInr(params, this.moduleRouter());
      if (response.respCode === SUCCESS) {
        // 回填数据
        this.model[this.currentRowIndex].extkey = row.ptaobjkey;
        this.model[this.currentRowIndex].ptainr = response.data.ptaobjinr;
        this.model[this.currentRowIndex].ptyinr = response.data.ptyinr;
        this.model[this.currentRowIndex].nam = response.data.nam;
        this.model[this.currentRowIndex].adrblk = response.data.enadr;
        // 回填角色数据
        this.setRoleData();
        // 此处为了回填数据时回调
        this.$emit("handleChange");
      }
      this.dialogTableVisible = false;
    },
    currentChange(num) {
      this.currentPage = num;
      this.getTableData();
    },
    beforeClose(done) {
      this.dialogTableVisible = false;
      this.currentPage = 1;
      done();
    },
    //获取表格数据索引,方便删除
    tableRowClassName({ row, rowIndex }) {
      Object.defineProperty(row, "row_index", {
        value: rowIndex,
        configurable: true,
        writable: true,
        enumerable: false
      });
    },
    // 记录选中行索引
    handleClick(row, column, event) {
      console.log(row);
      this.rowIndex = row.row_index;
      console.log("选择:" + this.rowIndex);
    },

    handleAdd() {
      let temp = {};
      for (let it of this.columns) {
        temp[it.dataIndex] = "";
      }
      this.model.push(temp);
      this.$emit("handleChange");
    },
    handleDelete() {
      if (this.model.length === 0) return;
      if (this.rowIndex === null) {
        this.rowIndex = this.model[this.model.length - 1].row_index; //没有选中删除最后一行
      }
      this.model.splice(this.rowIndex, 1);
      this.rowIndex = null;
      this.$emit("handleChange");
    },
    handleDetails(row) {
      console.log(12, row);
    }
  }
};
</script>
<style lang="less" scoped>
.el-dialog__body {
  height: calc(100% - 55px);
}
</style>