/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-09-28 10:11:43
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /TracerMethodology_PC/src/pages/UserMana/index.js
 */

import { PlusOutlined } from '@ant-design/icons';
import { Button, Popconfirm} from 'antd';
import React, { useState, useRef } from 'react';

import { PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormSelect, ProFormDependency } from '@ant-design/pro-form';
import UpdateForm from './updateForm';

import { getDistrictList, editDistrictList, delDistrict, addDistrict,getMainDistrictList } from './service';

const DistrictMana = () => {
  const columns = [
    {
      title: '医院/院区ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '医院名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      hideInSearch: false,
    },
    {
      title: '是否为主院',
      dataIndex: 'isHospital',
      key: 'isHospital',
      hideInSearch: true,
      ellipsis: true,
      render: (text) => <a>{text == 0 ? '是' : '否'}</a>,
    },
    {
      title: '医院标识',
      dataIndex: 'sign',
      key: 'sign',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '医院Id',
      dataIndex: 'parentId',
      key: 'parentId',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '主医院名',
      dataIndex: 'parentName',
      key: 'parentName',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createDateTime',
      key: 'createDateTime',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title:'操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="subscribeAlert"
          title="是否确定删除?"
          onConfirm={() => {
            setCurrentRow(record);
            delListHandler(record);
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const actionRef = useRef();
  const ref = useRef();   //新增表单
  const [currentRow, setCurrentRow] = useState({});

  /**
   *
   * @param {Boolean} bool 弹窗展示状态
   */
  const updateModalVisibleChange = (bool) => {
    handleUpdateModalVisible(bool);
    if (!bool) setCurrentRow(undefined);
  };

  //获取科室列表
  const getList = async (params = {}, sort, filter) => {
    const res = await getDistrictList(params);
    // console.log({res});
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

  /**
   *
   * @param {Object} value 删除项数据
   */
  const delListHandler = async (value) => {
    const resp = await delDistrict(value);
    // console.log({ resp });
    if (resp) {
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };

  // useEffect(()=>{
  //   CARequest('/api/costAccount/hosptail/list');
  // },[]);

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            新增
          </Button>
        ]}

        pagination={{
          pageSize: 10,
        }}
        search={{
          defaultCollapsed: false,
          labelWidth: 'auto',
        }}

      />

      <ModalForm
        title="新增医院"
        width="800px"
        labelCol={{ span: 3, offset: 3 }}
        layout={'horizontal'}
        formRef={ref}
        visible={createModalVisible}
        onVisibleChange={(bool) => {
          if (ref.current) {
            ref.current.resetFields();
          }
          handleModalVisible(bool);
        }}
        onFinish={async (value) => {
          const {name,isHospital,id,sign} = value;
          const success = await addDistrict(isHospital==0?{
            name,isHospital,sign
          }:{
            name,isHospital,parentId:id
          });
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="医院名"
          rules={[
            {
              required: true,
              message:'医院名是必填项',
            },
          ]}
          width="sm"
          name="name"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message:'请选择是否为主院',
            },
          ]}
          options={[
            {
              value: 0,
              label: '是',
            },
            {
              value: 1,
              label: '否',
            },
          ]}
          width="xs"
          name="isHospital"
          label="是否为主院"
        />

        <ProFormDependency name={['isHospital']}>
          {({ isHospital }) => {
            return isHospital == 0 ? (
              <ProFormText
                label="医院标识"
                rules={[
                  {
                    required: true,
                    message:'',
                  },
                ]}
                width="sm"
                name="sign"
              />
            ) : <></>;
          }}
        </ProFormDependency>
        <ProFormDependency name={['isHospital']}>
          {({ isHospital }) => {
            return isHospital == 1 ? (
              <ProFormSelect
                name="id"
                label="选择主医院"
                request={async () =>{
                      const resp = await getMainDistrictList();                      
                      if(resp){
                        return resp.map(item=>({
                          label:item.name,
                          value:item.id
                        }))
                      }
                }}
                placeholder=""
                width='sm'
                rules={[{ required: true, message: '请选择主医院ID' }]}
              />
            ) : <></>
          }}
        </ProFormDependency>
      </ModalForm>

      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          // console.log({ '编辑': value });
          const success = await editDistrictList(value);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        updateModalVisibleChange={updateModalVisibleChange}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default DistrictMana;
