/* 设备供应商
 * @Author: Li Hanlin
 * @Date: 2022-11-09 14:44:44
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2023-01-31 13:50:19
 */

import * as React from 'react';
import { useState, useMemo, useEffect, useRef } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import InitForm from '@/components/InitForm';
import ExtendField from '@/components/ExtendField';
import { doFetch } from '@/utils/doFetch';
import { Image, message, Divider } from 'antd';
import { ProDescriptions } from '@ant-design/pro-components';

function Supplier(props) {
  let actionRef = useRef(),
    formRef = useRef();
  const [drawer, setDrawer] = useState({
    visible: false,
  });

  const urlParams = {
    save: '/asset/equipmentSupplier/save',
    remove: '/asset/equipmentSupplier/deleteById',
    list: '/asset/equipmentSupplier/queryList',
    detail: '/asset/equipmentSupplier/query/detail',
    detail_nocp: '/asset/equipmentSupplier/queryById',
  };

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              // detailpath: urlParams.detail,
              // params: { id: row?.id },
              title: '编辑',
              val: 'only',
              type: 'edit',
              item: row,
              // onFinish: async (vals) => {
              //   let equipmentSupplierCharReqList = [];
              //   //console.log('id:', row.id);
              //   for (let i in vals) {
              //     if (!isNaN(Number(i))) {
              //       equipmentSupplierCharReqList.push({
              //         fieldId: i,
              //         fieldRealValue: vals[i],
              //       });
              //       delete vals[i];
              //     }
              //   }
              //   let params = {
              //     ...vals,
              //     id: row?.id,
              //     shopIdList: vals.shopId,
              //     equipmentSupplierCharReqList,
              //   };
              //   delete params.shopId;
              //   let res = await doFetch({
              //     url: urlParams.save,
              //     params,
              //   });
              //   if (res.code === '0000') {
              //     message.success('编辑成功！');
              //     setDrawer((s) => ({
              //       ...s,
              //       visible: false,
              //     }));
              //     actionRef.current.reload();
              //   }
              // },
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否删除该供应商?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            let res = await doFetch({ url: urlParams.remove, params: { id: row.id } });
            if (res.code === '0000') {
              message.success('删除成功！');
              setDrawer((s) => ({
                ...s,
                visible: false,
              }));
              actionRef.current.reload();
            }
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  const Details = () => {
    const columns = [
      {
        title: '供应商编号',
        dataIndex: 'supplierNo',
        key: 'supplierNo',
      },
      {
        title: '供应商名称',
        dataIndex: 'supplierName',
        key: 'supplierName',
      },
      { title: '公司官网', dataIndex: 'officialWebsite', key: 'officialWebsite' },
      {
        title: '联系电话',
        dataIndex: 'telephone',
        key: 'telephone',
      },
      {
        title: '公司邮箱',
        dataIndex: 'email',
        key: 'email',
      },
      {
        title: '地址',
        dataIndex: 'address',
        key: 'address',
      },
      {
        title: '状态',
        dataIndex: 'statusName',
        key: 'status',
      },
      {
        title: '评分',
        dataIndex: 'score',
        key: 'score',
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
      },
    ];

    const [newfieldscolumns, setnewfieldscolumns] = useState([]);
    const selectValueType = (type, options) => {
      switch (type) {
        case 1:
          return {
            valueType: 'input',
          };
        case 2:
          return {
            valueType: 'select',
            options,
          };
        case 3:
          return {
            valueType: 'radio',
            options,
          };
        case 4:
          return {
            valueType: 'select',
            options,
          };
        default:
          break;
      }
    };
    const [request, setrequest] = useState();
    useEffect(() => {
      const fn = async () => {
          let res = await doFetch({
            url: '/base/paFormField/queryList',
            params: {
              formId: '3',
            },
          });
          if (res?.data?.dataList) {
            let column = [];
            res?.data?.dataList?.forEach?.((el) => {
              column.push({
                ...selectValueType(el.fieldChar, el.valueList),
                title: el.fieldName,
                dataIndex: el.id,
                key: el.id,
              });
            });
            setnewfieldscolumns(column);
          }
        },
        fn2 = async () => {
          const res = await doFetch({
            url: urlParams.detail,
            params: { id: drawer?.item?.id },
          });
          let obj = {};
          res?.data?.data['equipmentSupplierCharList']?.forEach?.((it) => {
            obj[it?.fieldId] = it?.fieldRealValue;
          });

          setrequest(
            {
              ...(res?.data?.data ?? {}),
              ...obj,
            } ?? {},
          );
        };
      fn();
      fn2();
    }, []);
    return (
      <>
        <ProDescriptions dataSource={request} columns={columns} />
        <AutoTable
          pagetitle="联系信息"
          columns={[
            {
              title: '联系人',
              dataIndex: 'userName',
              key: 'userName',
              search: false,
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: '此项为必填项',
                  },
                ],
              },
            },
            {
              title: '手机号码',
              search: false,
              dataIndex: 'telephone',
              key: 'telephone',
            },
            {
              title: '邮箱',
              search: false,
              dataIndex: 'email',
              key: 'email',
            },
            {
              title: '职务',
              search: false,
              dataIndex: 'title',
              key: 'title',
              fieldProps: {
                placeholder: '请选择',
              },
              formItemProps: {
                rules: [
                  {
                    required: false,
                    message: '此项为必填项',
                  },
                ],
              },
            },
          ]}
          dataSource={request?.supplierUserList}
          resizeable={false}
          pagination={false}
        />
        <Divider />
        <h3 className="page-title" style={{ marginBottom: 16 }}>
          扩展字段
        </h3>
        <ProDescriptions dataSource={request} columns={newfieldscolumns} />
      </>
    );
  };
  const columns = useMemo(() => {
    let defcolumn = getcolumns(false, actionRef);
    defcolumn[1].render = (text, row) => {
      return (
        <a
          onClick={() => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              type: 'detail',
              item: row,
              val: 'only',
              title: row.supplierName + '的详细信息',
            }));
          }}
        >
          {row.supplierName}
        </a>
      );
    };
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => [edit(text, row, _, action), remove(text, row, _, action)],
    });
  }, []);

  const selectMoreDrawerType = (type) => {
    switch (type) {
      case 'detail':
        return <Details />;
      case 'add':
        return (
          <ExtendField
            defaultFormValue={drawer?.item}
            setDrawer={setDrawer}
            drawer={drawer}
            actionRef={actionRef}
            columns={columns}
            formId={'3'}
            // urlParams={urlParams}
            onFinish={async (vals) => {
              let equipmentSupplierCharReqList = [];
              for (let i in vals) {
                if (!isNaN(Number(i))) {
                  equipmentSupplierCharReqList.push({
                    fieldId: i,
                    fieldRealValue: vals[i],
                  });
                  delete vals[i];
                }
              }
              let params = {
                ...vals,
                id: drawer?.title == '编辑' ? drawer?.item?.id : '',
                equipmentSupplierCharReqList,
              };
              delete params.shopId;
              let res = await doFetch({
                url: urlParams.save,
                params,
              });
              if (res.code === '0000') {
                if (drawer?.title == '编辑') {
                  message.success('编辑成功！');
                } else {
                  message.success('新增成功！');
                }
                setDrawer((s) => ({
                  ...s,
                  visible: false,
                }));
                actionRef.current.reload();
              }
            }}
          />
        );
      case 'edit':
        return (
          <ExtendField
            setDrawer={setDrawer}
            drawer={drawer}
            actionRef={actionRef}
            columns={drawer?.item?.statusChangeable == 1 ? getcolumns(false) : getcolumns(true)}
            formId={'3'}
            urlParams={urlParams}
            onFinish={async (vals) => {
              let equipmentSupplierCharReqList = [];
              for (let i in vals) {
                if (!isNaN(Number(i))) {
                  equipmentSupplierCharReqList.push({
                    fieldId: i,
                    fieldRealValue: vals[i],
                  });
                  delete vals[i];
                }
              }
              let params = {
                ...vals,
                id: drawer?.title == '编辑' ? drawer?.item?.id : '',
                equipmentSupplierCharReqList,
              };
              delete params.shopId;
              let res = await doFetch({
                url: urlParams.save,
                params,
              });
              if (res.code === '0000') {
                if (drawer?.title == '编辑') {
                  message.success('编辑成功！');
                } else {
                  message.success('新增成功！');
                }
                setDrawer((s) => ({
                  ...s,
                  visible: false,
                }));
                actionRef.current.reload();
              }
            }}
          />
        );
      default:
        return null;
    }
  };
  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">设备供应商</h3>}
        columns={columns}
        path={urlParams.list}
        actionRef={actionRef}
        pageextra={'add'}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            disabled: false,
            type: 'primary',
            onClick: () => {
              setDrawer((s) => ({
                ...s,
                visible: true,
                item: {
                  status: 1,
                  score: 0,
                },
                title: '新增',
                detailpath: null,
                type: 'add',
                val: 'only',
              }));
            },
          },
        }}
      />

      <DrawerPro
        fields={columns}
        defaultFormValue={drawer?.item ?? {}}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            visible: false,
          }));
          actionRef.current.reload();
        }}
        {...drawer}
      >
        {selectMoreDrawerType(drawer?.type)}
      </DrawerPro>
    </div>
  );
}

export default Supplier;
