<template>
  <a-modal
    :open="open" :mask-closable="false" ok-text="确认" cancel-text="取消" title="选择买受方" width="60%"
    @update:open="$emit('update:open', $event)" @cancel="cancelSelect" @ok="confirmEdit"
  >
    <a-card>
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
        <a-button type="link" :icon="h(PlusCircleTwoTone)" @click="handleAddRow">新增</a-button>
        <a-input-search
          v-model:value="searchQuery" style="width: 300px;" placeholder="请输入买受方,电话,联系人进行查询" enter-button
          @search="handleSearch"
        />
      </div>
      <div style="height: 240px;">
        <a-table
          :columns="acceptorColumns" :data-source="acceptorDatas" row-key="id" bordered :pagination="false"
          size="small" row-class-name="editable-row" :scroll="{ y: 220 }" :row-selection="{
            type: 'radio',
            onChange: rowSelectedChange,
            selectedRowKeys: selectedKey,
          }"
        >
          <template #bodyCell="{ column, record, text, index }">
            <template v-if="column.dataIndex === 'operation'">
              <span v-if="record.isEditing">
                <a-button type="link" @click="handleSaveRow(record, index)">保存</a-button>
                <a-button type="link" danger @click="handleCancelRow(record, index)">取消</a-button>
              </span>
              <span v-else>
                <a-button type="link" @click="handleEditRow(record, index, true)">编辑</a-button>
                <a-button type="link" danger @click="handleCancelRow(record, index, true)">删除</a-button>
              </span>
            </template>
            <template v-else>
              <a-input v-if="record.isEditing" v-model:value="record[column.dataIndex]" size="small" />
              <span v-else>{{ text }}</span>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>

    <a-card style="margin-top: 8px;">
      <span>该买受方评价</span>
      <div style="height: 240px;">
        <a-table
          :columns="evaluateColumns" :data-source="evaluateData" row-key="id" bordered :pagination="false"
          size="small" :scroll="{ y: 220 }"
        />
      </div>
    </a-card>
  </a-modal>
</template>

<script setup>
import { message } from 'ant-design-vue';
import Common from '../common/Common.js';
import { queryAllApi, saveBuyerApi } from './api.js';
import { PlusCircleTwoTone } from '@ant-design/icons-vue';
import { ref, defineEmits, defineProps, h, onMounted } from 'vue';
import { acceptorAddColumn, evaluateColumn } from './assetConfig.js';


const emit = defineEmits(['update:open', 'getSelectInfo']);
const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
});

const acceptorColumns = ref(acceptorAddColumn);

const acceptorDatas = ref([]); // 买受方数据
const searchQuery = ref(''); // 查询参数

const selectedKey = ref([]); // 所选key值
const selectInfo = ref(null); // 所选数据
const evaluateData = ref([]); // 评价数据

// 选择买受方变化
const rowSelectedChange = (key, record) => {
  selectedKey.value = key;
  selectInfo.value = JSON.parse(JSON.stringify(record))[0];
};

// 关闭选择买受方
const cancelSelect = () => {
  emit('update:open', false);
};

// 确认选择买受方
const confirmEdit = () => {
  emit('update:open', false);
  emit('getSelectInfo', selectInfo.value);
};

// 查询
const handleSearch = searchValue => {
  searchAcceptor(searchValue);
};

// 添加一行新数据
const handleAddRow = () => {
  acceptorDatas.value.push({
    buyerName: '',
    phone: '',
    contactPerson: '',
    mainBusiness: '',
    address: '',
    isEditing: true,
  });
};

// 编辑行数据
const handleEditRow = record => {
  record.isEditing = true;
};

// 保存行数据
const handleSaveRow = record => {
  if (!record.buyerName) {
    message.warning('请输入买受方名称。');
    return;
  }
  if (!record.phone) {
    message.warning('请输入联系电话。');
    return;
  }
  if (!record.contactPerson) {
    message.warning('请输入联系人。');
    return;
  }
  if (!record.mainBusiness) {
    message.warning('请输入主营业务。');
    return;
  }
  if (!record.address) {
    message.warning('请输入地址。');
    return;
  }
  addAcceptor(record);
};

// 取消编辑，并删除该行  
const handleCancelRow = (record, index, isDelete) => {
  acceptorDatas.value.splice(index, 1);
  if (isDelete) deleteAcceptor(record.id);
};

onMounted(() => {
  searchAcceptor('');
});

// 查询买受方
const searchAcceptor = str => {
  queryAllApi(str).then(
    success => {
      if (success.errorCode === 0) {
        if (success.data) {
          acceptorDatas.value = success.data;
        }
      } else {
        message.warning(success.errorMessage);
      }
    },
    error => {
      Common.processException(error);
    },
  );


};

// 新增买受方
const addAcceptor = record => {
  const params = {
    ...record,
  };
  saveBuyerApi(params).then(
    success => {
      if (success.errorCode === 0) {
        message.success('新增买受方成功。');
        record.isEditing = false;
        searchAcceptor('');
      } else {
        message.warning(success.errorMessage);
      }
    },
    error => {
      Common.processException(error);
    },
  );
};

// 删除买受方
const deleteAcceptor = id => {
  $.ajax({
    url: Common.getApiURL('AcceptorResource/deleteAcceptor'),
    type: 'post',
    data: {
      AcceptorId: id,
    },

    beforeSend: function (request) {
      Common.addTokenToRequest(request);
    },
    success: function (data) {
      if (data.errorCode === 0) {
        message.success('删除成功');
        searchAcceptor('');
      } else {
        message.warning(data.errorMessage);
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      Common.processException(XMLHttpRequest);
    },
  });
};


const evaluateColumns = ref(evaluateColumn);
</script>

<style scoped>
.editable-row .ant-table-tbody>tr>td {
  transition: background 0.3s;
}

.editable-row .ant-table-tbody>tr.editing>td {
  background: #f5f5f5;
}

:deep(.ant-card-body) {
  padding: 12px;
}
</style>