import React, { useEffect, useState } from 'react';
import qs from 'query-string';
import { Button, Descriptions, message, Table, Modal } from 'antd';
import { ColumnsType } from 'antd/es/table';
// import { PriceModal } from '@/pages/goodsManage/productManage/comp/priceModal';
// import { AddEditDetailModal } from '@/pages/goodsManage/productManage/comp/addEditDetailModal';
import useOption from '~/common/hook/optionHook';
import { ProductSkuType, ProductSpecType } from '../produceList/propsType';
import { ProduceManageAPI } from '~/api';

const { confirm } = Modal;
function ProduceDetail(props: any) {
  // 基本信息
  const [detailData, setDetailData] = useState<ProductSkuType>();
  // 表格数据
  const [tableData, setTableData] = useState<ProductSpecType[]>([]);
  // 图片是否放大
  const [visibleImg, setVisibleImg] = useState<boolean>(false);
  // 当前放大图片
  const [currentImgList, setCurrentImgList] = useState<{ src: string }[]>([]);
  // 产品清单弹窗显示
  const [visibleList, setVisibleList] = useState<boolean>(false);
  // 当前放大图片
  const [listData, setListData] = useState([]);
  // 配置价格弹窗显示
  const [visiblePrice, setVisiblePrice] = useState<boolean>(false);
  // 当前配置价格数据
  const [priceData, setPriceData] = useState([]);
  // 配置价格弹窗显示
  const [visibleAddEdit, setVisibleAddEdit] = useState<boolean>(false);
  // 当前配置价格数据
  const [addEditData, setAddEditData] = useState<ProductSpecType>();
  // 按钮权限
  const btnAdd = useOption(22155);
  const btnSetPrice = useOption(22156);
  const btnEdit = useOption(22157);
  const btnDelete = useOption(22158);
  // 预览图片
  const previewImage = (url: string) => {
    setVisibleImg(true);
    setCurrentImgList([{ src: url }]);
  };
  // 关闭图片放大
  const setVisibleEvent = () => {
    setVisibleImg(false);
  };
  // 查看产品清单
  const handleList = (arr: any) => {
    setListData(arr);
    setVisibleList(true);
  };
  // 关闭产品清单
  const handleListClosed = () => {
    setListData([]);
    setVisibleList(false);
  };
  // 打开配置价格弹窗
  const handlePrice = (arr: any) => {
    setPriceData(arr);
    setVisiblePrice(true);
  };
  // 关闭配置价格弹窗
  const handlePriceClosed = () => {
    setPriceData([]);
    setVisiblePrice(false);
  };
  // 打开新增弹窗
  const handleAdd = () => {
    const { id } = qs.parse(props.location.search);
    setAddEditData({
      createTime: '',
      id: 0,
      partNo: '',
      productSkuId: id as unknown as number,
      specImage: '',
      specName: '',
      versionDesc: '',
    });
    setVisibleAddEdit(true);
  };
  // 打开编辑弹窗
  const handleEdit = (arr: ProductSpecType) => {
    setAddEditData(arr);
    setVisibleAddEdit(true);
  };
  // 关闭新增编辑弹窗
  const handleAddEditClosed = () => {
    paginationChange(pagination.current, pagination.pageSize);
    setAddEditData(undefined);
    setVisibleAddEdit(false);
  };
  // 删除产品
  const handleDelete = (record: ProductSpecType) => {
    confirm({
      title: '提示',
      content: '删除后此数据将会丢失，确定删除吗？',
      async onOk() {
        const res: any = await ProduceManageAPI.removeProductSpec({ id: record.id });
        if (res.code !== '200') {
          return message.error(res.message);
        }
        if (!res.result) {
          await message.success('操作成功');
          await paginationChange(pagination.current, pagination.pageSize);
          return;
        }
        message.info({
          content: (
            <div style={{ textAlign: 'left' }}>
              {res.result.goodsName && (
                <div>
                  <div style={{ color: 'red' }}>删除失败，已被商品关联</div>
                  <div>关联商品为： {res.result.goodsName.join(',')}</div>
                </div>
              )}
              {res.result.industrySkuName && (
                <div>
                  <div style={{ color: 'red' }}>删除失败，已被方案关联</div>
                  <div>关联方案SKU为： {getTipInfo(res.result.industrySkuName)}</div>
                </div>
              )}
            </div>
          ),
          duration: 2,
          // key: date,
          // onClick: () => {
          //   message.destroy(date);
          // },
        });
      },
    });
  };
  // 表格结构
  const columns: ColumnsType<ProductSpecType> = [
    { title: '规格名称', dataIndex: 'specName', align: 'center' },
    {
      title: '规格图片',
      dataIndex: 'specImage',
      align: 'center',
      render: (text: string) => {
        return (
          <img
            style={{ width: '50px', height: '50px' }}
            src={text}
            alt='图片'
            onClick={() => {
              previewImage(text);
            }}
          />
        );
      },
    },
    { title: '版本描述', dataIndex: 'versionDesc', align: 'center' },
    { title: '料号', dataIndex: 'partNo', align: 'center' },
    {
      title: '操作',
      align: 'center',
      width: '250px',
      render: (text: string, record: ProductSpecType) => {
        return (
          <div>
            {btnSetPrice ? (
              <Button
                type='link'
                onClick={() => {
                  handlePrice(record);
                }}
              >
                配置价格
              </Button>
            ) : (
              ''
            )}
            {btnEdit ? (
              <Button
                type='link'
                onClick={() => {
                  handleEdit(record);
                }}
              >
                编辑
              </Button>
            ) : (
              ''
            )}
            {btnDelete ? (
              <Button type='link' onClick={() => handleDelete(record)}>
                删除
              </Button>
            ) : (
              ''
            )}
          </div>
        );
      },
    },
  ];
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 获取基本信息
  const getDetailData = async () => {
    const { id } = qs.parse(props.location.search);
    const res: any = await ProduceManageAPI.getProductSkuDetail({ id });
    if (res && res.code === '200') {
      setDetailData(res.result);
    }
  };
  // 获取表格数据
  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res: any = await ProduceManageAPI.listPageProductSpec({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      productSkuId: qs.parse(props.location.search).id,
    });
    if (res && res.code === '200') {
      // console.log("res -->", res);
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        pageSize,
        current: pageNo,
        totalPage,
      });
      setTableData(list);
    } else {
      message.warning(res.message);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 返回上一页
  const handleBack = () => {
    history.go(-1);
  };
  // 获取提示信息
  const getTipInfo = (data: any) => {
    return data.map((v: any) => `${v.industrySkuName}(${v.industrySpecNames})`).join('、');
  };
  useEffect(() => {
    // if (!props.location.search) return;
    // getDetailData().then();
    // getTableList().then();
  }, []);
  return (
    <div className='detail-wrap'>
      <Descriptions
        title='一、基本信息'
        bordered
        column={1}
        size='middle'
        labelStyle={{ width: '200px' }}
        style={{ width: '100%' }}
        extra={
          <Button type='primary' onClick={handleBack}>
            返回
          </Button>
        }
      >
        <Descriptions.Item label='产品名称'>{detailData?.productName}</Descriptions.Item>
        <Descriptions.Item label='产品目录'>{detailData?.directoryName}</Descriptions.Item>
        <Descriptions.Item label='产品类型'>{detailData?.typeName}</Descriptions.Item>
        <Descriptions.Item label='型号'>{detailData?.model}</Descriptions.Item>
        <Descriptions.Item label='产品品牌'>{detailData?.productBrand}</Descriptions.Item>
      </Descriptions>
      <Descriptions
        title='二、方案规格'
        column={1}
        size='middle'
        labelStyle={{ width: '200px' }}
        style={{ marginTop: '20px' }}
      >
        {btnAdd ? (
          <Descriptions.Item>
            <Button type='primary' onClick={handleAdd}>
              新增规格
            </Button>
          </Descriptions.Item>
        ) : (
          ''
        )}
        <Descriptions.Item>
          <Table
            size='small'
            dataSource={tableData}
            columns={columns}
            rowKey='id'
            style={{ width: '100%' }}
            bordered
            pagination={{
              total: pagination.total,
              pageSize: pagination.pageSize,
              current: pagination.current,
              showSizeChanger: true,
              showQuickJumper: true,
              onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
              showTotal: (total, range) =>
                `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
            }}
          />
        </Descriptions.Item>
      </Descriptions>
      {/*<PriceModal visible={visiblePrice} closed={handlePriceClosed} data={priceData} />*/}
      {/*<AddEditDetailModal*/}
      {/*  visible={visibleAddEdit}*/}
      {/*  closed={handleAddEditClosed}*/}
      {/*  data={addEditData}*/}
      {/*/>*/}
    </div>
  );
}
export default ProduceDetail;
