
import { Modal, Button, message, Form, Upload, Tag ,Popconfirm} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import { GetDeviceVesionPage, AddDeviceVesion, DelDeviceVesion, UpdateDeviceVesion, GetProductList,UpdateStatus } from "./services"
import { history } from 'umi';
const key = 'message';

//添加
const handleAdd = async (fields) => {
  try {
    message.loading('正在添加', key);
    await AddDeviceVesion(JSON.stringify(fields)).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.success('添加成功');
        return true;
      } else {
        message.error('添加失败');
        return false;
      }
    });
  } catch (error) {
    message.error('添加失败请重试！');
    return false;
  }
};


//修改
const handleUpdate = async (fields) => {
  try {
    message.loading('正在修改', key);
    message.destroy(key);
    await UpdateDeviceVesion(JSON.stringify(fields)).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.success('修改成功',);
        return true;
      } else {
        message.success('修改失败');
        return false;
      }
    });
  } catch (error) {
    message.error('修改失败请重试！');
    return false;
  }
};


//删除
const handleRemove = async (selectedRows) => {
  try {
    message.loading('正在删除');
    let ids = [];
    selectedRows.forEach((item) => {
      ids.push(item.id);
    });
    await DelDeviceVesion(ids).then((r) => {
      if (r.data) {
        message.success('删除成功');
        return true;
      } else {
        message.error(r.errors);
        return false;
      }
    });
  } catch (error) {
    message.error('删除失败请重试！');
    return false;
  }
};


const GoodsTypeManage = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const actionRef = useRef();
  const [DictData, setDictData] = useState([]);
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isAddGoodsTemplate,setIsAddGoodsTemplate]=useState(false);
  const [form] = Form.useForm();
  const props = {
    beforeUpload: (file) => {
      if (
        file.type !== 'application/vnd.ms-excel' &&
        file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ) {
        message.error(`${file.name} 不是 exelce 文件`);
      }
      return file.type == 'application/vnd.ms-excel' ||
        file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ? true
        : Upload.LIST_IGNORE;
    },
    name: 'file',
    data: { "id": currentRow?.id, "deviceClientType": currentRow?.deviceTypeKey, "version": currentRow?.vesion,"isAddGoodsTemplate":isAddGoodsTemplate},
    action: '/saasbase/api/goods/goodstemplateexport',
    headers: {
      Authorization: 'Bearer  ' + localStorage.getItem('token')
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      setIsAddGoodsTemplate(false);
      if (info.file.status === 'done') {
        setIsModalOpen(false);
        actionRef.current.reloadAndRest();
        message.success(`${info.file.name} 文件上传成功.`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上载失败.`);
      }
    }
  };
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key'
    },
    {
      title: '版本号',
      dataIndex: 'vesion',
      valueType: 'textarea',
    },
    {
      title: '所属产品',
      dataIndex: 'productName',
      valueType: 'textarea',
    },
    // {
    //   title: '是否存在模板',
    //   dataIndex: 'templatePath',
    //   valueType: 'textarea',
    //   hideInSearch: true,
    //   render: (_, record) => [
    //     <div>
    //       <Tag color="#f50" style={{ textAlign: "center", display: (record.templatePath == null||record.templatePath == "") ? "none" : "block" }}  >存在模板</Tag>
    //       <Tag style={{ textAlign: "center", display: (record.templatePath == null||record.templatePath == "")? "block" : "none" }} color="#2db7f5">无模板</Tag>
    //     </div>],
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 700,
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
            // form.setFielsValue(record)
          }} > 更新</a>,
          <Popconfirm
          type="primary"
          key="primary11"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            DelDeviceVesion([record.id]).then((r) => {

              if (r.data) {
                message.success('删除成功');
                actionRef.current.reloadAndRest();
              } else {
                message.error(r.errors);
              }
              
            });
          }}
          onCancel={() => { }}
        >
          <a href="#">删除</a>
        </Popconfirm>,
        // <a
        //   key="config"
        //   onClick={() => {
        //     setCurrentRow(record);
        //     setIsModalOpen(true);
        //     setIsAddGoodsTemplate(false);
        //   }} > 上传设备工艺模型</a>,
        // <a
        //   key="config"
        //   onClick={() => {
        //     setCurrentRow(record);
        //     setIsModalOpen(true);
        //     setIsAddGoodsTemplate(true);
        //   }} > 上传商品工艺模版</a>,
        // <a
        //   key="config"
        //   href={record.templatePath}

        // > 下载工艺模板</a>,
        <a
        key="config"
        onClick={() => {
          history.push({
            pathname: '/device/productmanage',
            query: {
              isAdd: false,
              values: record,
              tabStatus: 'basis'
            },
          });
        }} > 管理</a>,
      ],
    },
  ];
  useEffect(() => {
    GetProductList().then((r) => {
      var arr = r.data;
      let data = {};
      if (r.succeeded) {
        var list = [];
        arr.forEach((item) => {
          data[item.code] = { text: item.code };
          list.push({
            label: item.name,
            text:item.name,
            id: item.id,
          });
        });
        //setDicDataAny(data);
        setDictData(list);
      }
    });
  }, [])
  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle="设备版本"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              // form.setFielsValue(currentRow)
              handleModalVisible(true);
            }} >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var data = [];
          var total = 0;
          await GetDeviceVesionPage(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
        </FooterToolbar>
      )}

      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = handleUpdate(value);
          } else {
            success = handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
          }
          actionRef.current.reloadAndRest();
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
        form={form}
        dicData={DictData}
      />
      <Modal title="上传工艺模版" open={isModalOpen} footer={null} onCancel={() => { setIsModalOpen(false) }}>
        <Upload {...props} maxCount={1}>
          <Button >导入工艺模版</Button>
        </Upload>
      </Modal>

    </PageContainer>
  );
};

export default GoodsTypeManage;
