<template>
  <div>
    <div style="margin-top: 28px">
      <el-form
        ref="ruleFormRef"
        class="ip-form"
        :inline="true"
        :model="shareData"
        :rules="rules"
        label-width="84px"
        label-position="left"
      >
        <el-form-item label="企业账号：" prop="tenantCode" style="margin-right: 100px">
          <el-input
            v-model="shareData.tenantCode"
            placeholder="请输入企业账号"
            class="company-input"
          />
          <el-button
            type="primary"
            size="small"
            plain
            style="margin-left: 10px"
            @click="verifyAccount"
            >验证</el-button
          >
        </el-form-item>
        <el-form-item label="权限设置：" prop="permission">
          <el-radio-group v-model="shareData.permission" class="ml-4">
            <el-radio v-for="item in authorityTypeSelect" :label="item.value" :key="item.value">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="企业名称："
          prop="tenantName"
          class="company-name"
          style="margin-right: 160px"
        >
          <el-input
            v-model="shareData.tenantName"
            disabled
            placeholder=""
            readonly
            style="width: 200px; height: 32px"
          />
          <div v-if="shareData.tenantName" class="verify-success">账号验证成功</div>
        </el-form-item>
        <el-form-item label="分享时间：" prop="time">
          <el-radio-group v-model="shareData.time" class="ml-4" @change="changeTime">
            <el-radio v-for="item in timeTypeSelect" :label="item.value" :key="item.value"
              >{{ item.label }}
            </el-radio>
          </el-radio-group>
          <div
            ><el-input
              v-model="shareData.days"
              placeholder="请输入"
              :readonly="shareData.time === 'Indefinite'"
              class="day-input"
            />
            <span>/天</span></div
          >
        </el-form-item>
        <el-form-item label="备注：" prop="notes">
          <el-input v-model="shareData.remark" placeholder="请输入备注" style="width: 765px" />
        </el-form-item>
        <el-button type="primary" @click="handleConfirm" class="confirm">确定</el-button>
        <el-form-item label="分享企业：" prop="shareList" class="company-table">
          <BasicTable
            :columns="getColumns(handleEditState)"
            :data-source="cameraShareList"
            :row-key="(row) => row.code"
            :action-column="actionColumn"
            :showHeader="false"
            :tableSetting="{
              size: false,
              redo: false,
              fullscreen: false,
              striped: false,
              setting: false,
            }"
            :striped="true"
            ref="tableRef"
            style="height: 200px"
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { h, reactive, ref, onMounted } from 'vue';
  import { BasicColumn, BasicTable, TableActionIcons } from '@/components/Table';
  import { CameraShareItem, CameraShowItem } from '../type';
  import deleteIcon from '@/assets/images/table/table-delete.png';
  import { authorityTypeSelect, timeTypeSelect, getColumns } from '../constant';
  import useCameraShare from '../stores/useCameraShare';
  import { getVerify } from '@/api/camera/camera-share';
  import dayjs from 'dayjs';
  import { ElMessage, FormInstance, FormRules } from 'element-plus';

  const useShare = useCameraShare();
  const { cameraShareList, queryCameraId, conditionSearch, handleDel, handleAdd, handleEdit } =
    useShare;

  const props = defineProps<{ formData?: CameraShowItem | null }>();

  const rules = reactive<FormRules>({
    tenantCode: [{ required: true, message: '请输入企业账号', trigger: 'blur' }],
    permission: [{ required: true, message: '', trigger: 'change' }],
    tenantName: [{ required: true, message: '请验证企业账号', trigger: 'change' }],
    time: [{ required: true, message: '', trigger: 'change' }],
    shareList: [{ required: true, message: '', trigger: 'blur' }],
  });

  // onMounted(() => {});
  onMounted(() => {
    //获取数据
    queryCameraId.value = props.formData?.id;
    console.log('queryCameraId', props.formData?.code);
    conditionSearch();
  });

  const ruleFormRef = ref<FormInstance>();

  const shareData = ref<CameraShareItem>({
    tenantCode: undefined,
    toTenantId: undefined,
    permission: '0',
    tenantName: '',
    time: 'Indefinite',
    days: undefined,
    remark: '',
    endTime: '',
  });

  // 将修改列表中的
  const handleEditState = (row) => {
    const editData = {
      id: row.id as number,
      connected: row.connected ? false : true,
    };
    handleEdit(editData);
  };

  const handleDelete = (row) => {
    handleDel(row.id);
  };

  //操作列
  const actionColumn: BasicColumn = reactive({
    width: 200,
    title: '操作',
    prop: 'action',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableActionIcons as any, {
        space: 20,
        color: '#629bf9',
        style: 'img',
        size: 16,
        actionIcons: [
          {
            label: '删除',
            icon: deleteIcon,
            onClick: handleDelete.bind(null, record.row),
          },
        ],
      });
    },
  });

  const verifyAccount = () => {
    // shareData.value.name = 'C' + shareData.value.account;
    getVerify(shareData.value.tenantCode!).then((res) => {
      if (res) {
        shareData.value.tenantName = res.tenantName;
        shareData.value.toTenantId = res.tenantId;
      } else {
        shareData.value.tenantName = '';
        shareData.value.toTenantId = undefined;
        ElMessage.error('企业账号验证失败');
      }
    });
  };

  const changeTime = () => {
    if (shareData.value.time === 'Indefinite') {
      shareData.value.days = undefined;
    }
  };

  const resetData = () => {
    shareData.value.tenantCode = undefined;
    shareData.value.toTenantId = undefined;
    shareData.value.tenantName = '';
    shareData.value.permission = '0';
    shareData.value.time = 'Indefinite';
    shareData.value.days = undefined;
    shareData.value.remark = '';
    shareData.value.endTime = '';
  };

  const handleConfirm = () => {
    if (!ruleFormRef.value) return;

    ruleFormRef.value.validate((valid) => {
      if (!valid) {
        return;
      }
      if (shareData.value.time === 'Indefinite') {
        shareData.value.endTime = dayjs().add(-1, 'day').format('YYYY-MM-DD HH:mm:ss');
      } else {
        shareData.value.endTime = dayjs()
          .add(shareData.value.days!, 'day')
          .format('YYYY-MM-DD HH:mm:ss');
      }

      //接口
      const currentDate = new Date();
      console.log('currentDate', currentDate);
      const addShareItem = {
        cameraId: props.formData?.id,
        toTenantId: shareData.value.toTenantId,
        permission: shareData.value.permission,
        endTime: shareData.value.endTime,
        isAdd: false,
        remark: shareData.value.remark,
      };
      queryCameraId.value = props.formData?.id;
      handleAdd(addShareItem); //数据未调整
      resetData();
    });
  };
</script>

<style scoped>
  .ip-form {
    width: 900px;
    display: flex;
    flex-wrap: wrap;
    align-content: space-around;
  }

  :deep(.el-form-item__label) {
    font-size: 14px;
    color: #363636;
    padding: 0;
  }
  :deep(.el-form--inline .el-form-item) {
    display: flex;
    margin-right: 0;
    margin-bottom: 28px;
  }

  .company-input {
    width: 200px;
    height: 32px;
  }

  .day-input {
    width: 64px;
    height: 32px;
    margin-left: 10px;
    margin-right: 4px;
  }
  .verify-success {
    position: absolute;
    right: -100px;

    /* margin-right: 100px; */
    color: rgb(142, 215, 33);
  }

  .confirm {
    position: relative;
    left: 800px;
  }

  .company-table {
    margin-top: 70px;
    margin-left: -60px;
  }

  .company-name {
    margin-right: 160px;
    position: relative;
  }
</style>
