import { PlusOutlined } from '@ant-design/icons';
import { Modal, Button, message,Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import {
  GetDeviceInfoPage,
  GetProductList,
  AddDeviceInfo,
  UpdateDeviceInfo,
  DelDeviceInfo,
  GetDeviceType,
  GetDeviceVersions,
  CopyDevice,
  TechnologyTemplateExport,
  GoodsTemplateExport,
} from './services';
import { gettree } from '../../org/orgamange/service';

import { values } from 'lodash';
const key = 'message';


const GoodsTypeManage = () => {
  const [storeType, setStoreType] = useState();

  const [storeTypeArray, setStoreTypeArray] = useState([]);
  const [OrgList, setOrgList] = useState([]);
  const [OrgListArray, setOrgListArray] = useState([]);
  const [dicDataAny, setDicDataAny] = useState([]);
  const [dicData, setDicData] = useState([]);
  const [deviceVersion, setDeviceVersion] = useState([]);
   /** 新建/更新窗口的弹窗 */
   const [createModalVisible, handleModalVisible] = useState(false);
   /** 分布更新窗口的弹窗 */
   const actionRef = useRef();
   const [currentRow, setCurrentRow] = useState();
   const [selectedRowsState, setSelectedRows] = useState([]);
  //初始化数据
  useEffect(() => {
   
    function initOrgList() {
      gettree().then((r) => {
        inittree(r.data);
        function inittree(datas) {
          for (var i in datas) {
            if (datas[i]['type'] == 2 || datas[i]['type'] == 3) {
              datas[i]['disabled'] = false;
            } else {
              datas[i]['disabled'] = true;
            }

            if (datas[i].children) {
              inittree(datas[i].children);
            }
          }
        }
        setOrgList(r.data);
        let list = {};
        formateData(r.data);
        function formateData(datas) {
          for (var i in datas) {
            list[datas[i]['disabled']] = true;
            list[datas[i]['value']] = { text: datas[i]['title'] };
            if (datas[i].children) {
              formateData(datas[i].children);
            }
          }
        }
        setOrgListArray(list);
      });
    }
    initOrgList();
    initDeviceType();
    function intDicData() {
      GetProductList().then((r) => {
        var arr = r.data;
        let data = {};
        if (r.succeeded) {
          var list = [];
          arr.forEach((item) => {
            data[item.name] = { text: item.name };
            list.push({
              id: item.id,
              label: item.name,
              text:item.name,
            });
          });
          setDicDataAny(data);
          setDicData(list);
        }
      });
    }
    intDicData();
    initDeviceVersion();
  }, []);
  const initDeviceType = () => {
    GetDeviceType().then((data) => {
      let list = {};
      let list2 = [];
      data.data.forEach((item) => {
        list2.push({
          label: item.name,
          text:item.name,
          value: item.id,
        });
        list[item.id] = { text: item.name };
      });
      setStoreTypeArray(list2);
      setStoreType(list);
    });
  };
  const initDeviceVersion = async () => {
    const response = await GetDeviceVersions();
    if (response.statusCode == 200) {
      setDeviceVersion(response.data);
    } else {
      message.error('获取设备版本失败');
    }
  };

  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      valueType: 'textarea',
    },
    {
      title: '所属产品',
      dataIndex: 'productName',
      valueEnum: dicDataAny,
      hideInSearch: true,
    },
    {
      title: '产品版本',
      dataIndex: 'productVersionName',
      search: false,
    },
    {
      title: '支持功能',
      dataIndex: 'technologyOrBom',
      search: false,
      valueEnum: {
        0: { text: '工艺',  },
        1: { text: '配方',},
      },
    },
    // {
    //   title: '归属门店',
    //   dataIndex: 'orgId',
    //   search: false,
    //   valueEnum: OrgListArray,
    // },
    {
      title: '设备标签',
      dataIndex: 'deviceTypeId',
      valueEnum: storeType,
    },
    {
      title: '设备唯一key',
      dataIndex: 'autoKey',
      search: false,
    },
    // {
    //   title: '归属门店唯一key',
    //   dataIndex: 'orgKey',
    //   search: false,
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 400,
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,
      <Popconfirm
      type="primary"
      key="primary"
      title="确认删除吗？"
      okText="是"
      cancelText="否"
      onConfirm={async () => {
        await DelDeviceInfo([record.id]).then((r) => {
          if(r.data){
            message.success('删除成功，即将刷新');
            actionRef.current.reloadAndRest();
          }else{
            message.error('删除失败');
          }
          
        });
      }}
      onCancel={() => { }}
    >
      <a href="#">删除</a>
    </Popconfirm>,
        // <a
        //   key="copy"
        //   onClick={() => {
        //     CopyDevice({ id: record.id }).then((r) => {
        //       if (r.data) {
        //         actionRef.current.reloadAndRest();
        //       }
        //     });
        //   }}
        // >
        //   复制
        // </a>,
        // <a
        //   key="upload-goods"
        //   onClick={() => {
        //     setCurrentRow(record);
        //     setDeviceFoodModal(true);
        //   }}
        // >
        //   绑定商品
        // </a>,
        // <a
        //   key="add"
        //   onClick={() => {
        //     setCurrentRow(record);
        //     setStockModal(true);
        //   }}
        // >
        //   库存原料
        // </a>,
        <a
          key="add"
          onClick={async () => {
            const response = await TechnologyTemplateExport(record.id);
            if (response == '') {
              message.error('当前模板不存在！');
              return;
            }
            // const blob = new Blob([response]);
            // const url = URL.createObjectURL(blob);
            // console.log(blob, url);
            // const link = document.createElement('a');
            // link.download = `工艺模板_${new Date(Date.now()).toLocaleString()}.xls`;
            // link.href = url;
            // link.click();
            const link = document.createElement('a');
            link.href = response;
            link.click();
          }}
        >
          导出工艺模版
        </a>,
      ],
    },
  ];

//添加
const handleAdd = async (fields) => {
 
    await AddDeviceInfo(JSON.stringify(fields)).then((r) => {
    
      if (r.succeeded) {
        message.success('添加成功');
        handleModalVisible(false);
        actionRef.current.reloadAndRest();
      } else {
        message.error(r.errors)
        return false;
      }
    });
 
};
//修改
const handleUpdate = async (fields) => {
    await UpdateDeviceInfo(JSON.stringify(fields)).then((r) => {
      if (r.succeeded) {
        message.success('添加成功');
        handleModalVisible(false);
        actionRef.current.reloadAndRest();
      } else {
        message.error(r.errors)
        return false;
      }
    });
 
};

//删除
const handleRemove = async (selectedRows) => {
  try {
    message.loading('正在删除');
    let ids = [];
    selectedRows.forEach((item) => {
      ids.push(item.id);
    });
    await DelDeviceInfo(ids).then((r) => {
      if (r.data) {
        message.success('删除成功');
        return true;
      } else {
        message.success('删除失败');
        return false;
      }
    });
  } catch (error) {
    message.error('删除失败请重试！');
    return false;
  }
};
  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle="设备信息"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        scroll={{ x: 2000 }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
          // <Button
          //   onClick={async () => {
          //     await handleRemove(selectedRowsState);
          //     setSelectedRows([]);
          //     actionRef.current?.reloadAndRest?.();
          //   }}
          // >
          //   删除
          // </Button>,
        ]}
        request={async (params) => {
          var data = [];
          var total = 0;
          await GetDeviceInfoPage(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;
              {/* <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.id, 0)} 万
              </span> */}
            </div>
          }
        >
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}

      <CreateForm
        storeType={storeTypeArray}
        OrgData={OrgList}
        dicData={dicData}
        initDeviceType={initDeviceType}
        onFinish={async (value) => {
          if (value.id) {
            handleUpdate(value);
          } else {
            handleAdd(value);
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        deviceVersions={deviceVersion}
        values={currentRow || {}}
      />
 
    </PageContainer>
  );
};

export default GoodsTypeManage;
