<template>
  <BasicModal
    width="70%"
    @register="registerModal"
    v-bind="$attrs"
    :title="type == 'edit' ? '土地使用权人信息 (添加、修改、删除多土地使用权人信息后，需点击“保存”按钮进行保存)' : '查看'"
  >
    <template #footer> </template>
    <a-space style="width: 100%" class="flex justify-end">
      <a-button class="editable-add-btn" type="primary" v-if="type == 'edit'" @click="handleAdd" style="margin-bottom: 8px">添加</a-button>
      <a-button class="editable-add-btn" type="primary" v-if="type == 'edit'" @click="save" style="margin-bottom: 8px">确认</a-button>
      <!-- <a-button class="editable-add-btn" type="primary" @click="close" style="margin-bottom: 8px">返回</a-button> -->
    </a-space>
    <a-table :columns="columns" :data-source="dataSource" bordered>
      <template #headerCell="{ column }">
        <template v-for="col in ['tdsyqrlx', 'gsyyzzh', 'syqdwmc', 'qdHstdsqysj']" :key="col">
          <template v-if="column.dataIndex === col">
            <span>
              {{ column.title }}
            </span>
            <span style="color: red"> * </span>
          </template>
        </template>
      </template>
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.dataIndex === 'tdsyqrlx'">
          <div>
            <a-select
              v-if="(editableData[record.dataIndex] || !text) && type == 'edit'"
              v-model:value="record.tdsyqrlx"
              placeholder="请选择"
              :options="options"
              style="width: 100%"
            ></a-select>
            <div v-else @click="edit(record.dataIndex)">{{ getType(text) }}</div>
          </div>
        </template>
        <template v-if="column.dataIndex === 'qdHstdsqysj'">
          <div>
            <a-date-picker
              v-if="(editableData[record.dataIndex] || !text) && type == 'edit'"
              v-model:value="record.qdHstdsqysj"
              value-format="YYYY-MM-DD"
            />
            <div v-else @click="edit(record.dataIndex)">{{ text }}</div>
          </div>
        </template>
        <template v-for="col in ['syqdwmc', 'gsyyzzh', 'proportion', 'frdb', 'lxr']" :key="col">
          <template v-if="column.dataIndex === col">
            <div>
              <a-input v-if="(editableData[record.dataIndex] || !text) && type == 'edit'" v-model:value="record[col]" style="margin: -5px 0" />
              <template v-else>
                <div @click="edit(record.dataIndex)"> {{ text }}</div>
              </template>
            </div>
          </template>
        </template>
        <template v-if="column.dataIndex === 'lxdh'">
          <div>
            <a-input-number
              style="width: 100%"
              :controls="false"
              :maxlength="11"
              :min="1"
              v-if="(editableData[record.dataIndex] || !text) && type == 'edit'"
              v-model:value="record.lxdh"
            />
            <template v-else>
              <div @click="edit(record.dataIndex)"> {{ text }}</div>
            </template>
          </div>
        </template>
        <template v-if="column.dataIndex === 'operation' && type == 'edit'">
          <div>
            <a-button type="primary" @click="handleDel(index)" size="small">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  import { reactive, ref, UnwrapRef, watch, nextTick } from 'vue';

  const props = defineProps({
    data: Object,
    type: {
      type: String,
      default: 'edit',
    },
  });

  const { createMessage } = useMessage();
  const [registerModal, { setModalProps, closeModal }] = useModalInner();

  const columns = [
    {
      title: '土地使用权人类型',
      dataIndex: 'tdsyqrlx',
      width: '15%',
    },
    {
      title: '土地使用权人名称',
      dataIndex: 'syqdwmc',
      width: '15%',
      // slots: { customRender: 'age' },
    },
    {
      title: '统一社会信用代码（身份证号码）',
      dataIndex: 'gsyyzzh',
      width: '15%',
      // slots: { customRender: 'address' },
    },
    {
      title: '取得使用权日期',
      dataIndex: 'qdHstdsqysj',
    },
    {
      title: '占比',
      dataIndex: 'proportion',
    },
    {
      title: '法人代表',
      dataIndex: 'frdb',
    },
    {
      title: '联系人',
      dataIndex: 'lxr',
    },
    {
      title: '电话',
      dataIndex: 'lxdh',
      width: '15%',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      colSpan: props.type == 'edit' ? 1 : 0,
    },
  ];
  interface DataItem {
    tdsyqrlx: string;
    syqdwmc: string;
    gsyyzzh: string;
    qdHstdsqysj: string;
    proportion: string;
    frdb: string;
    lxr: string;
    lxdh: string;
  }

  const data: DataItem[] = [];
  const dataSource = ref(data);

  watch(
    () => props.data,
    async (val: any) => {
      val &&
        nextTick(async () => {
          dataSource.value = val;
          console.log(val, 'val');
          console.log(dataSource.value);
        });
    },
    { deep: true, immediate: true }
  );

  const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

  const edit = (key: string) => {
    editableData[key] = cloneDeep(dataSource.value.filter((item: any) => key === item.dataIndex)[0]);
  };
  const save = (key: string) => {
    let flg = true;
    for (let i = 0; i < dataSource.value.length; i++) {
      if (!dataSource.value[i].tdsyqrlx || !dataSource.value[i].syqdwmc || !dataSource.value[i].gsyyzzh || !dataSource.value[i].qdHstdsqysj) {
        createMessage.error('请填写必填信息');
        flg = false;
        break;
      }
      if (dataSource.value[i].lxdh) {
        const math = /^1[3456789]\d{9}$/;
        if (!math.test(dataSource.value[i].lxdh)) {
          createMessage.error('请填写正确的手机号');
          flg = false;
          break;
        }
      }
    }
    console.log(dataSource.value, ' dataSource.value');
    if (!flg) return;
    delete editableData[key];
    closeModal();
    return dataSource.value;
  };

  const handleAdd = () => {
    // key需要获取数据最后一条id +1
    const newData = {
      tdsyqrlx: '',
      syqdwmc: '',
      gsyyzzh: '',
      qdHstdsqysj: '',
      proportion: '',
      frdb: '',
      lxr: '',
      lxdh: '',
    };
    dataSource.value.push(newData);
  };
  const options = ref([
    {
      label: '土地使用权人（企业）',
      value: '1',
    },
    {
      label: '土地使用权人（自然人）',
      value: '2',
    },
    {
      label: '政府',
      value: '3',
    },
    {
      label: '其他',
      value: '4',
    },
  ]);
  // 回显土地使用权人类型
  function getType(v) {
    const res = options.value.filter((item: any) => item.value == v);
    return res[0].label;
  }
  const handleDel = (key: any) => {
    dataSource.value = dataSource.value.filter((item: any, index: any) => index != key);
  };

  defineExpose({
    save,
  });
</script>
