import React, { useState, useEffect, useRef } from "react";
import { connect } from "react-redux";
import moment from "moment";
import qs from "qs";
import {
   Button,
   Form,
   Table,
   Pagination,
   Popover,
   Tag,
   Skeleton,
   Popconfirm,
   Row,
} from "@douyinfe/semi-ui";
import { SimpleFileDownButton, VideoPlayModal, SkeletonScreen, Setup } from "$components";
// import "../style.less";
import ApplyModal from "../components/applyModal";
// import RemarksModal from "../components/remarksModal";
// import SideSheets from "../components/sideSheet";
// import { accessType } from "./nvr";
import '../style.less'

const ApplicationCenter = (props) => {
   const { dispatch, actions, user, loading, applicationData } = props;
   const { applicationCenter } = actions;
   const [modalName, setModalName] = useState(false); //创建或修改
   const [setup, setSetup] = useState(false);  //表格设置是否显现
   const [applyModal, setApplyModal] = useState(false);
   const [setupp, setSetupp] = useState([]);
   const [query, setQuery] = useState({ limit: 10, page: 0 }); //页码信息
   const [appData, setAppData] = useState(null); //应用id
   const APPLICATION = 'application'
   const pageLimit = useRef({ limit: 10, page: 0 });
   const limits = useRef(); //每页实际条数


   const columns = [
      {
         title: "序号",
         dataIndex: "",
         render: (text, r, index) => {
            return index + 1;
         },
      },
      {
         title: "应用名称",
         dataIndex: "name",
         key: "name",
         render: (text, r, index) => {
            return r?.name.length > 8 ? <Popover
               position='top'
               content={
                  <article style={{ padding: 12 }}>
                     {r?.name}
                  </article>
               }
            >{
                  `${r?.name.substr(0, 8)}...`}
            </Popover> : r?.name
         },
      },
      {
         title: "APPID",
         dataIndex: "appKey",
         key: "appId",

      },
      {
         title: "Secret Key",
         dataIndex: "appSecret",
         key: "secretKey",

      },
      {
         title: "操作",
         width: "20%",
         dataIndex: "",
         render: (_, row) => {
            return (
               <div style={{ display: "flex" }}>
                  <Button
                     theme="borderless"
                     onClick={() => {
                        setApplyModal(true)
                        setModalName(true)
                        setAppData(row)
                     }}
                  >
                     修改
                  </Button>
                  {row?.forbidden ? (
                     <Button
                        theme="borderless"
                        onClick={() => {
                           dispatch(applicationCenter.putApplication({ appId: row?.id, forbidden: !row?.forbidden })).then(() => details())
                        }}
                     >
                        启用
                     </Button>
                  ) : (
                     <Popconfirm
                        title={<div style={{ width: 200 }}>禁用后，应用系统引入的页面及能力将会暂时失效，请谨慎操作。</div>}
                        arrowPointAtCenter={false}
                        showArrow={true}
                        position="topRight"
                        onConfirm={() => {
                           dispatch(applicationCenter.putApplication({ appId: row?.id, forbidden: !row?.forbidden })).then(() => {
                              setQuery({ limit: pageLimit.current.limit, page: pageLimit.current.page })
                           })
                        }}
                     >
                        <Button theme="borderless">禁用</Button>
                     </Popconfirm>
                  )}
                  <Popconfirm
                     title={<div style={{ width: 200 }}>删除后，应用系统引入的页面及能力将会永久失效，请谨慎操作。</div>}
                     arrowPointAtCenter={false}
                     width={300}
                     showArrow={true}
                     position="topRight"
                     onConfirm={() => {
                        dispatch(applicationCenter.delApplication(row?.id)).then(() => {
                           if (pageLimit.current.page > 0 && limits.current < 2) {
                              setQuery({ limit: pageLimit.current.limit, page: pageLimit.current.page - 1 })
                           } else {
                              setQuery({ limit: pageLimit.current.limit, page: pageLimit.current.page })
                           }
                        })
                     }}
                  >
                     <Button theme="borderless">删除</Button>
                  </Popconfirm>

               </div >
            );
         },
      }
   ];

   //获取表格属性设置
   function attribute () {
      const arr = localStorage.getItem(APPLICATION)
         ? JSON.parse(localStorage.getItem(APPLICATION))
         : [];

      const column = [
         {
            title: "创建时间",
            dataIndex: "createTime",
            key: "createTime",
            render: (_, r, index) => {
               return moment(r.createTime).format("YYYY-MM-DD HH:mm:ss");
            },
         },
         {
            title: "创建账号",
            dataIndex: "createUserId",
            key: "account",
            render: (_, r, index) => {
               return r?.createUser?.name
            },
         },
         {
            title: "应用类型",
            dataIndex: "type",
            key: "applicationType",
            render: (_, r, index) => {
               const types = { web: 'web', app: 'app', wxapp: '小程序', other: '其他' }
               return r?.type?.map((item, index) => types[item] + ';')

            },
         },
      ];

      for (let i = 0; i < arr.length; i++) {
         let colum = column.filter((item) => {
            return item.key === arr[i];
         });
         columns.splice(i + 4, 0, colum[0]);
      }
      setSetupp(columns);
   }
   const tableList = [//表格属性
      {
         title: '详情信息',
         list: [
            { name: "创建时间", value: "createTime" },
            { name: "创建账号", value: "account" },
            { name: "应用类型", value: "applicationType" },
         ]
      },
   ];

   //获取应用信息
   const details = (data) => {
      pageLimit.current = query
      dispatch(applicationCenter.getApplication(pageLimit.current)).then((res) => {
         limits.current = res.payload.data.data.length
      });
   }
   useEffect(() => {
      details()
   }, [query])

   useEffect(() => {
      //初始化表格显示设置
      localStorage.getItem(APPLICATION) == null
         ? localStorage.setItem(
            APPLICATION,
            JSON.stringify(["createTime",])
         )
         : "";
      attribute();
   }, [])
   return (
      <>
         <div style={{ position: "" }}>
            <video
               id="cameraBanner"
               autoPlay
               loop
               muted
               style={{ width: "100%", objectFit: "cover", height: 171 }}
               src="/assets/video/camera_banner.mp4"
               type="video/mp4"
            />
            <div style={{ position: "absolute", top: 12 }}>
               <div
                  style={{
                     fontSize: 22,
                     paddingTop: 15,
                     marginLeft: 21,
                  }}
               >
                  应用管理
               </div>
               <div
                  style={{
                     fontSize: 14,
                     paddingTop: 18,
                     marginLeft: 20,
                  }}
               >
                  创建接口对应子系统的APPID及能力调用时所需的秘钥。
               </div>
               <div
                  style={{
                     fontSize: 14,
                     marginTop: 28,
                     marginLeft: 21,
                     width: 89,
                     height: 32,
                     lineHeight: 32 + "px",
                     textAlign: "center",
                     backgroundColor: "#D9EAFF",
                     color: "#1859C1",
                     cursor: "pointer",
                  }}
                  onClick={() => {
                     setApplyModal(true)
                  }}
               >
                  创建应用
               </div>
            </div>
         </div>
         <div style={{ background: "#FFFFFF", marginTop: 5 }}>
            <div
               style={{
                  width: "100%",
                  display: "flex",
                  justifyContent: "space-between",
                  padding: "13px 20px",
               }}
            >
               <div
                  style={{
                     width: 64,
                     height: 22,
                     fontSize: 16,
                     fontfAmily: "PingFangSC-Medium, PingFang SC",
                     fontWeight: "bold",
                     color: "rgba(0, 0, 0, 0.85)",
                     lineHeight: "22px",
                  }}
               >
                  应用列表
               </div>
               <div>
                  <Button
                     style={{
                        width: 32,
                        height: 32,
                        background: "#D9D9D9",
                        borderadius: 3,
                        marginRight: 20,
                     }}
                     type="primary"
                     key="primary"
                     onClick={() => {
                        setSetup(true);
                        // setcameraSetup(true);
                     }}
                  >
                     <img
                        src="/assets/images/background/setup.png"
                        alt="设置"
                        style={{ width: 18, height: 18 }}
                     />
                  </Button>
                  {/* <SimpleFileDownButton src="camera/export" /> */}
               </div>
            </div>
            <Skeleton
               loading={false}
               active={true}
               placeholder={SkeletonScreen()}
            >
               <Table
                  columns={setupp.filter((s) => s)}
                  dataSource={applicationData.data}
                  bordered={false}
                  empty="暂无数据"
                  style={{
                     padding: "0px 20px",
                  }}
                  pagination={false}
               />
            </Skeleton>
            <div
               style={{
                  display: "flex",
                  justifyContent: "flex-end",
                  padding: "20px 20px",
               }}
            >
               <span style={{ lineHeight: "30px" }}>
                  共{applicationData.total}个设备
               </span>
               <Pagination
                  className="22"
                  total={applicationData.total}
                  showSizeChanger
                  currentPage={query.page + 1}
                  pageSizeOpts={[10, 20, 30, 40]}
                  onChange={(currentPage, pageSize) => {
                     setQuery({ limit: pageSize, page: currentPage - 1 });
                     pageLimit.current = { limit: pageSize, page: currentPage - 1 }
                  }}
               />
            </div>

         </div>

         {/*表格设置*/}
         {setup ? (
            <Setup
               tableType={APPLICATION}
               tableList={tableList}
               close={() => {
                  setSetup(false);
                  attribute();
               }}
            />
         ) : (
            ""
         )}

         {applyModal ? (
            <ApplyModal
               visible={true}
               modalName={modalName}
               appData={appData}
               close={() => {
                  setApplyModal(false)
                  setModalName(false)
                  setAppData(null)
                  details()
               }}
            />
         ) : (
            ""
         )}

      </>
   )
}

function mapStateToProps (state) {
   const { global, applicationData } = state;
   return {
      actions: global.actions,
      applicationData: applicationData.data || {}
   };
}

export default connect(mapStateToProps)(ApplicationCenter);
