<template>
  <div>
    <a-row :gutter="16" style="margin-bottom: 20px">
      <a-col :span="24">
        <a-button type="primary" @click="submitAll" :loading="loading" style="margin-right: 6px"> 保存流程 </a-button>
        <a-button @click="addNew" :loading="loading"> 新增节点 </a-button>
      </a-col>
    </a-row>
    <a-table
      :columns="columns"
      :rowKey="(record, index) => index"
      :data-source="data"
      :pagination="false"
      :scroll="{ x: true }"
      :loading="tableLoading"
      class="j-table-force-nowrap"
      size="middle"
    >
      <template #bodyCell="{ column, record, index, text }">
        <template v-if="['name', 'description', 'timeDesc', 'proportion'].includes(column.dataIndex)">
          <div>
            <a-input
              v-if="editableData[record.key]"
              style="margin: -5px 0"
              v-model:value="editableData[record.key][column.dataIndex]"
              @change="(e) => handleChange(e.target.value, record.key, column)"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>

        <template v-if="column.dataIndex === 'id'">
          <a-tag color="pink" @click="up(record, index)" style="cursor: pointer" :class="index == 0 ? 'disabled' : ''">
            <a-icon type="arrow-up" />
          </a-tag>
          <a-tag color="blue" @click="down(record, index)" style="cursor: pointer" :class="index == data.length - 1 ? 'disabled' : ''">
            <a-icon type="arrow-down" />
          </a-tag>
        </template>

        <template v-if="column.dataIndex === 'action'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.key]">
              <a @click="() => save(record.key)" style="margin-right: 10px">保存</a>
              <a-popconfirm title="确定取消吗?" @confirm="cancel(record.key)">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a v-if="editableData[record.key]" disabled @click="() => edit(record.key)">编辑</a>
              <a v-else @click="() => edit(record.key)">编辑</a>
              <a-divider type="vertical" />
              <a v-if="editableData[record.key]" disabled @click="() => deleteRow(index)">删除</a>
              <a v-else @click="() => deleteRow(index)">删除</a>
            </span>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
  import { getAction, postAction } from '/@/api/manage/manage';
  import { reactive, ref, UnwrapRef } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';

  const columns = [
    {
      title: '节点名称',
      dataIndex: 'name',
      scopedSlots: { customRender: 'name' },
    },
    {
      title: '节点描述',
      dataIndex: 'description',
      scopedSlots: { customRender: 'description' },
    },
    {
      title: '预计时间',
      dataIndex: 'timeDesc',
      scopedSlots: { customRender: 'timeDesc' },
    },
    {
      title: '权重',
      dataIndex: 'proportion',
      scopedSlots: { customRender: 'proportion', title: 'proportionTitle' },
    },
    {
      title: '排序',
      dataIndex: 'id',
      scopedSlots: { customRender: 'id' },
    },
    {
      title: '操作',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' },
    },
  ];

  let data = ref([{}]);

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

  const hostId = ref('');
  const tableLoading = ref(false);
  const loading = ref(false);
  const url = ref('');
  let record = reactive({});
  let cacheData = reactive([{}]);

  const { createMessage } = useMessage();

  function submitAll() {
    let d = data.value;
    let proportion = 0;
    for (let i in d) {
      proportion += parseInt(d[i].proportion);
    }
    if (parseInt(proportion) !== 100) {
      createMessage.warn('权重之和应为100');
      return;
    }
    loading.value = true;
    // for(let i in d){
    //   delete d[i].key
    // }
    postAction('/adweb/executeNode/saveFlowTemplate', d, 120000)
      .then((res) => {
        loading.value = false;
        if (res.code == 200) {
          createMessage.success('保存成功');
        } else {
          createMessage.warn(res.message);
        }
      })
      .catch((e) => {
        createMessage.warn('保存数据失败！');
      });
  }
  function addNew() {
    data.value.push({
      createTime: null,
      delFlag: 0,
      description: '',
      finTime: null,
      finUid: null,
      hostId: hostId,
      id: '',
      name: '',
      nodeType: 3,
      proportion: null,
      sort: 1,
      status: null,
      timeDesc: null,
      type: 1,
      key: data.value.length,
    });
    cacheData = data.value;
  }
  //排序
  function up(r, i) {
    if (i == 0) {
      return;
    }
    data.value.splice(i - 1, 0, data[i]);
    data.value.splice(i + 1, 1);
  }
  function down(r, i) {
    if (i == data.value.length - 1) {
      return;
    }
    data.value.splice(i + 2, 0, data[i]);
    data.value.splice(i, 1);
  }
  function deleteRow(i) {
    data.value.splice(i, 1);
  }
  function onClose() {
    data.value = [];
  }
  function init(r, t) {
    record = r;
    if (t == 'seo') {
      url.value = '/adweb/executeNode/querySEOTemplateFlow?planId=' + r.id;
    } else if (t == 'enquiry') {
      url.value = '/adweb/executeNode/queryEnquiryVerifyTemplateFlow';
    } else {
      url.value = '/adweb/executeNode/querySiteBuildTemplateFlow';
    }
    showStep();
  }
  function showStep() {
    tableLoading.value = true;

    getAction(url.value, {})
      .then((res) => {
        tableLoading.value = false;
        if (res.success) {
          res.result.map((item, index) => {
            data.value.push(Object.assign({}, item, { key: index }));
            cacheData = data.value;
            hostId.value = res.result[0].hostId;
          });
        }
      })
      .catch((e) => {
        createMessage.warn('获取数据失败！', e.message());
      });
  }
  function handleChange(value, key, column) {
    const newData = [...data.value];
    const target = newData.filter((item) => key === item.key)[0];

    if (target) {
      target[column] = value;
      data.value = newData;
    }
  }
  // function edit(key) {
  //   const newData = [...data.value];
  //   const target = newData.filter((item) => key === item.key)[0];
  //   editingKey.value = key;
  //   if (target) {
  //     target.editable = true;
  //     data.value = newData;
  //   }
  // }
  // function save(key) {
  //   const newData = [...data.value];
  //   const newCacheData = [...cacheData];
  //   const target = newData.filter((item) => key === item.key)[0];
  //   const targetCache = newCacheData.filter((item) => key === item.key)[0];
  //   if (target && targetCache) {
  //     delete target.editable;
  //     data.value = newData;
  //
  //     console.log(data.value, '123123');
  //     Object.assign(targetCache, target);
  //     cacheData = newCacheData;
  //   }
  //   editingKey.value = '';
  // }

  const edit = (key: string) => {
    editableData[key] = cloneDeep(data.value.filter((item) => key === item.key)[0]);
  };
  const save = (key: string) => {
    Object.assign(data.value.filter((item) => key === item.key)[0], editableData[key]);
    delete editableData[key];
  };
  const cancel = (key: string) => {
    delete editableData[key];
  };

  // function cancel(key: string) {
  //   delete data.value[key];
  // }

  defineExpose({ onClose, init });
</script>

<style scoped lang="less">
  .ant-tag.disabled {
    cursor: no-drop !important;
    opacity: 0.3;
  }
</style>
