import {useState} from "react";
import Taro, {useDidShow} from '@tarojs/taro'
import {Button, Cell, CellGroup, Space, Empty, ConfigProvider, Divider} from '@nutui/nutui-react-taro'
import {Dongdong, ArrowRight, CheckNormal, Checked} from '@nutui/icons-react-taro'
import {View} from '@tarojs/components'
import {${entity}} from "@/api/${package.ModuleName}/${table.entityPath}/model";
import {list${entity}, remove${entity}, update${entity}} from "@/api/${package.ModuleName}/${table.entityPath}";

const ${entity}List = () => {
  const [list, setList] = useState<${entity}[]>([])
<% var hasIsDefaultField = false; %>
<% for(field in table.fields){ %>
<% if(field.propertyName == 'isDefault'){ %>
<% hasIsDefaultField = true; %>
<% } %>
<% } %>
<% if(hasIsDefaultField){ %>
  const [selectedItem, setSelectedItem] = useState<${entity}>()
<% } %>

  const reload = () => {
    list${entity}({
      // 添加查询条件
    })
      .then(data => {
        setList(data || [])
<% if(hasIsDefaultField){ %>
        // 设置默认选中项
        setSelectedItem(data.find(item => item.isDefault))
<% } %>
      })
      .catch(() => {
        Taro.showToast({
          title: '获取数据失败',
          icon: 'error'
        });
      })
  }

<% if(hasIsDefaultField){ %>
  const onDefault = async (item: ${entity}) => {
    if (selectedItem) {
      await update${entity}({
        ...selectedItem,
        isDefault: false
      })
    }
    await update${entity}({
<% var primaryKey = 'id'; %>
<% for(field in table.fields){ %>
<% if(field.keyFlag){ %>
<% primaryKey = field.propertyName; %>
<% } %>
<% } %>
      ${primaryKey}: item.${primaryKey},
      isDefault: true
    })
    Taro.showToast({
      title: '设置成功',
      icon: 'success'
    });
    reload();
  }

  const selectItem = async (item: ${entity}) => {
    if (selectedItem) {
      await update${entity}({
        ...selectedItem,
        isDefault: false
      })
    }
    await update${entity}({
      ${primaryKey}: item.${primaryKey},
      isDefault: true
    })
    setTimeout(() => {
      Taro.navigateBack()
    },500)
  }
<% } %>

  const onDel = async (id?: number) => {
    await remove${entity}(id)
    Taro.showToast({
      title: '删除成功',
      icon: 'success'
    });
    reload();
  }

  useDidShow(() => {
    reload()
  });

  if (list.length == 0) {
    return (
      <ConfigProvider>
        <div className={'h-full flex flex-col justify-center items-center'} style={{
          height: 'calc(100vh - 300px)',
        }}>
          <Empty
            style={{
              backgroundColor: 'transparent'
            }}
            description="暂无数据"
          />
          <Space>
            <Button onClick={() => Taro.navigateTo({url: '/${package.ModuleName}/${table.entityPath}/add'})}>新增${table.comment!'数据'}</Button>
          </Space>
        </div>
      </ConfigProvider>
    )
  }

  return (
    <>
      {list.map((item, _) => (
        <Cell.Group key={item.${primaryKey}}>
<% if(hasIsDefaultField){ %>
          <Cell className={'flex flex-col gap-1'} onClick={() => selectItem(item)}>
<% } else { %>
          <Cell className={'flex flex-col gap-1'}>
<% } %>
            <View>
<% var displayFields = []; %>
<% for(field in table.fields){ %>
<% if(field.propertyName != 'id' && field.propertyName != 'createTime' && field.propertyName != 'updateTime' && field.propertyName != 'isDefault'){ %>
<% displayFields.add(field); %>
<% if(displayFields.size() >= 2) break; %>
<% } %>
<% } %>
<% if(displayFields.size() > 0){ %>
              <View className={'font-medium text-sm'}>{item.${displayFields[0].propertyName}}</View>
<% } %>
            </View>
<% if(displayFields.size() > 1){ %>
            <View className={'text-xs'}>
              {item.${displayFields[1].propertyName}}
            </View>
<% } %>
          </Cell>
          <Cell
            align="center"
<% if(hasIsDefaultField){ %>
            title={
              <View className={'flex items-center gap-1'} onClick={() => onDefault(item)}>
                {item.isDefault ? <Checked className={'text-green-600'} size={16}/> : <CheckNormal size={16}/>}
                <View className={'text-gray-400'}>默认选项</View>
              </View>
            }
<% } %>
            extra={
              <>
                <View className={'text-gray-400'} onClick={() => onDel(item.${primaryKey})}>
                  删除
                </View>
                <Divider direction={'vertical'}/>
                <View className={'text-gray-400'}
                      onClick={() => Taro.navigateTo({url: '/${package.ModuleName}/${table.entityPath}/add?id=' + item.${primaryKey}})}>
                  修改
                </View>
              </>
            }
          />
        </Cell.Group>
      ))}
    </>
  );
};

export default ${entity}List;
