import React, { Fragment, useState, useEffect, useRef, useMemo } from 'react';
import { Table, Icon, message, Spin, Button, Form, DatePicker, Modal, Divider, Select, Input } from 'antd';
import { useRequest, useModel } from '@umijs/max';
import FirmModal from './ManufacturerModal';
import dayjs from 'dayjs';
const { RangePicker } = DatePicker;
import { stringify } from 'qs';
const pageSize = 10;
import {
  queryMfrList,
  queryCreaterList,
  editMfr,
  deleteMfr,
  saveMfr
} from '@/services/manufacturer'
function ManufacturerList(props) {
  const {
    projectId = 1,
    data,
  } = props;
  const { user } = useModel('userInfo');
  const [visible, setVisible] = useState(false);
  const [curItem, setCurItem] = useState(null);
  const [formDisabled, setFormDisabled] = useState(false);
  const [total, setTotal] = useState(0);
  const [formData, setFormData] = useState({ start_time: "", end_time: "", project_id: projectId * 1, is_super: user?.IsSuper || false, page: 1, page_size: pageSize });
  const queryMfrListRequest = useRequest(queryMfrList, {
    manual: true,
    onSuccess: data => {
      console.log(data);
      setFormData({ ...formData, page_size: pageSize })
      setTotal(data.count);
    }
  });
  const queryCreaterListRequest = useRequest(queryCreaterList, {});
  const saveMfrRequest = useRequest(saveMfr, {
    manual: true,
    onSuccess: () => {
      message.success('新增成功');
      queryList({ ...formData, page: 1 })
      queryCreaterListRequest.run({})
    }
  });
  const editMfrRequest = useRequest(editMfr, {
    manual: true,
    onSuccess: () => {
      message.success('编辑成功');
      queryList({ ...formData, page: 1 })
      queryCreaterListRequest.run({})
    }
  });
  const deleteMfrRequest = useRequest(deleteMfr, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功');
      queryList({ ...formData, page: 1 })
      queryCreaterListRequest.run({})
    }
  });
  const loading = useMemo(() => {
    var loading = queryMfrListRequest.loading || saveMfrRequest.loading || queryCreaterListRequest.loading || editMfrRequest.loading;
    return loading
  }, [queryMfrListRequest.loading, saveMfrRequest.loading, queryCreaterListRequest.loading, editMfrRequest.loading]);
  const columns = [
    {
      title: '供应商名称',
      dataIndex: 'name',
    },
    {
      title: '税号',
      dataIndex: 'tax_code',
    },
    {
      title: '地址',
      dataIndex: 'address'
      // render: (record) => {
      //   return moment(record.lab_time).format('YYYY-MM-DD')
      // }

    },
    {
      title: '联系人',
      dataIndex: 'contact',
    },
    {
      title: '联系方式',
      dataIndex: 'phone_number'
      // render: (record) => {
      //   return moment(record.create_time).format('YYYY-MM-DD')
      // }
    },
    {
      title: '开户银行',
      dataIndex: 'bank_account',
    },
    {
      title: '银行账号',
      dataIndex: 'bank_account',
    },
    {
      title: '创建人',
      dataIndex: 'created_by',
    },
    {
      title: '创建时间',
      render: (record) => {
        return dayjs(record.created_on).format('YYYY-MM-DD')
      }
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <>
            <a style={{ color: "#4096ff" }} onClick={() => {
              setCurItem(record);
              setFormDisabled(false);
              setVisible(true);
            }}>编辑</a>
          </>
          <>
            <Divider type="vertical" />
            <a style={{ color: "#4096ff" }} onClick={() => {
              handleDeleteItem(record);
            }}> 删除</a>
          </>
          <>
            <Divider type="vertical" />
            <a style={{ color: "#4096ff" }} onClick={() => {
              setCurItem(record);
              setVisible(true);
              setFormDisabled(true);
            }}>详情</a>
          </>
        </Fragment>
      ),
    },
  ];
  const onCancel = () => {
    setVisible(false)
  }
  const handleDeleteItem = record => {
    console.log(record);
    Modal.confirm({
      title: '提醒',
      content: `确认该条记录吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        deleteMfrRequest.run({ project_id: 1, id: record.id, deleted_by: user?.CName })
      },
    });
  }
  const handleExportChange = async () => {
    const data = {
      project_id: 1,
      is_super: user?.IsSuper || false,
      created_by: formData.created_by || ''
    };
    window.downloadFile(`/api/supplier/v1/supplier/export?${stringify(data)}`, '供应商列表.xlsx', false);
  };
  const handleSearch = () => {
    console.log(formData);
    let value = {
      project_id: projectId * 1,
      start_time: formData.start_time,
      end_time: formData.end_time,
      page_size: pageSize,
      page: 1,
      is_super: user?.IsSuper || false,
      created_by: formData.created_by || '',
      name: formData.name || ''
    }
    queryList(value);
  }
  const queryList = fieldsValue => {
    console.log(fieldsValue);
    setFormData(fieldsValue);
    var isSuper = user?.IsSuper || false;
    var created_by = isSuper ? fieldsValue.created_by || '' : user?.CName || undefined
    queryMfrListRequest.run({ ...fieldsValue, created_by })
  }
  const onDateChange = data => {
    let start_time = '';
    let end_time = '';
    if (data?.length > 0) {
      start_time = dayjs(data[0]).format('YYYY-MM-DD');
      end_time = dayjs(data[1]).format('YYYY-MM-DD');
    }
    setFormData({ ...formData, start_time: start_time, end_time: end_time })
  }
  const onOk = fieldsValue => {
    console.log(fieldsValue);
    setVisible(false);
    if (curItem != null)
      editMfrRequest.run({ ...fieldsValue, project_id: 1, updated_by: user?.CName, id: curItem.id })
    else
      saveMfrRequest.run({ ...fieldsValue, project_id: 1, created_by: user?.CName })
  }
  const onChange = name => {
    setFormData({ ...formData, created_by: name })
  }
  const onPaginationChange = pagination => {
    var tempFormData = { ...formData, page: pagination.current }
    setFormData(tempFormData)
    queryList(tempFormData);
  }
  const onInputChange = e => {
    setFormData({ ...formData, name: e.target.value })
  }
  useEffect(() => {
    queryList({ ...formData })
  }, []);
  return (
    <>
      <Form>
        <div style={{ display: 'flex', flexWrap: 'wrap' }}>
          <div style={{ margin: '0 24px' }}>
            <Form.Item label="日期:">
              <RangePicker onChange={onDateChange} />
            </Form.Item>
          </div>
          {
            user?.IsSuper && <div style={{ margin: '0 24px' }}>
              <Form.Item label="创建人:">
                <Select
                  onChange={onChange}
                  options={queryCreaterListRequest?.data?.list || []}
                  style={{ width: 180 }}
                  allowClear
                />
              </Form.Item>
            </div>
          }
          <div style={{ margin: '0 24px' }}>
            <Form.Item style={{ margin: '0px 24 0 24px' }} label="供应商名称:">
              <Input placeholder="请输入供应商名称" onChange={e => { onInputChange(e) }} />
            </Form.Item>
          </div>
          <div style={{ display: 'flex' }}>
            <Form.Item>
              <Button style={{ marginLeft: 24 }} type="primary" onClick={() => { handleSearch() }}>
                查询
              </Button>
            </Form.Item>
            <Button style={{ marginLeft: 10 }} loading={loading} type="primary" onClick={() => {
              setCurItem(null);
              setVisible(true)
            }}>
              新增
            </Button>
            <Button style={{ marginLeft: 10 }} loading={loading} onClick={() => handleExportChange()} type="primary">
              导出
            </Button>
          </div>
        </div>
      </Form>
      <Table
        rowKey='id'
        loading={loading}
        columns={columns}
        dataSource={queryMfrListRequest?.data?.list}
        pagination={{ current: formData.page, total: total, page_size: pageSize }}
        onChange={onPaginationChange}
      />
      <FirmModal
        projectId={projectId}
        visible={visible}
        onCancel={onCancel}
        onOk={onOk}
        item={curItem}
        disabled={formDisabled}
      ></FirmModal>
    </>
  )
}

export default ManufacturerList;