<template>
  <div class="padding" style="height: 700px; overflow: auto" v-if="baseData1">
    <div class="info-box">
      <div class="back_color padding">
        <a-descriptions :title="baseData1.dataName" :column="4" style="width: 80%">
          <a-descriptions-item label="创建人" style="width: 150px">{{
            baseData1.createUserName
          }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ baseData1.createDate }}</a-descriptions-item>
          <a-descriptions-item label="最后修改人" style="width: 150px">{{
            baseData1.modifyUserName
          }}</a-descriptions-item>
          <a-descriptions-item label="修改时间">{{ baseData1.modifyDate }}</a-descriptions-item>
        </a-descriptions>
        <div
          >&nbsp;
          <a-button v-if="baseData1.state != '1'" @click="handleEdit">修改</a-button>

          <a-button style="margin-left: 10px" v-if="baseData1.state != '1'" @click="handleDelete"
            >删除</a-button
          >
          <a-button style="margin-left: 10px" @click="handlePrint">打印</a-button>
          <!-- <a-button style="margin-left: 10px" @click="handleExport">导出</a-button> -->
          <a-button
            v-if="baseData1.state != '1'"
            type="primary"
            style="margin-left: 10px"
            @click="handleFinish(baseData1)"
            >结束盘点</a-button
          >
          <!-- 
                <a-button style="margin-left: 8px;">删除</a-button> -->
        </div>
        <div style="position: absolute; right: 12px; top: 12px">
          <a-image
            src="/src/assets/images/check_finish.png"
            :preview="false"
            v-if="baseData1.state == '1'"
          />
          <a-image src="/src/assets/images/check_in.png" :preview="false" v-else />
        </div>
      </div>
      <div class="back_color padding marginTop">
        <a-descriptions title="基础信息" :column="2">
          <a-descriptions-item label="盘点编码">{{ baseData1.dataCode }}</a-descriptions-item>
          <a-descriptions-item label="盘点主题">{{ baseData1.dataName }}</a-descriptions-item>
          <a-descriptions-item label="盘点日期">{{ baseData1.dataDate }}</a-descriptions-item>
          <a-descriptions-item label="仓库名称">
            <div v-if="baseData1.dataStorage">
              <span v-for="(re, i) in baseData1.dataStorage.split(',')" :key="i">
                <span v-for="item in storeOptions" :key="item.key">
                  <span v-if="item.value == re">{{ i > 0 ? ',' : '' }}{{ item.label }}</span>
                </span>
              </span>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="盘点人员">{{ baseData1.dataUserName }}</a-descriptions-item>

          <a-descriptions-item label="备注" :span="2">{{ baseData1.remark }}</a-descriptions-item>
        </a-descriptions>
      </div>
      <div class="back_color padding marginTop">
        <a-descriptions title="物品信息">
          <a-descriptions-item>
            <a-table
              v-if="baseData1.mesWarehouseCheckDetailList"
              :columns="filterColum(columnsProp.columns)"
              :bordered="true"
              :pagination="false"
              :data-source="baseData1.mesWarehouseCheckDetailList"
              :scroll="{ x: 'max-content' }"
              style="width: 100%"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key !== 'action'">
                  <template v-if="column.dataIndex === 'index'">
                    {{ index + 1 }}
                  </template>
                </template>
                <template v-if="column.dataIndex === 'areaId'">
                  <span v-if="record.areaId">
                    <span v-for="item in areaOptions" :key="item.key">
                      <span v-if="item.value == record.areaId">{{ item.label }}</span>
                    </span>
                  </span>
                </template>
                <template v-if="column.dataIndex === 'locationId'">
                  <span v-if="record.locationId">
                    <span v-for="item in locationOptions" :key="item.key">
                      <span v-if="item.value == record.locationId">{{ item.label }}</span>
                    </span>
                  </span>
                </template>
              </template>
            </a-table>
          </a-descriptions-item>
        </a-descriptions>
      </div>
      <div class="back_color padding">
        <a-descriptions title="附件">
          <a-descriptions-item>
            <!-- <a-upload v-model:file-list="baseData1.dataFile" :multiple="true" listType="picture-card">
          </a-upload> -->
            <Upload
              :disabled="!rowData.isUpdate"
              v-model:value="baseData1.dataFile"
              listType="dragger"
              tip="支持扩展名：.doc  .docx  .pdf  .jpg ..."
              :style="{ display: 'none' }"
            />
          </a-descriptions-item>
        </a-descriptions>
      </div>

      <a-divider />
      <a-modal
        :maskClosable="false"
        :title="titleModa"
        v-model:visible="visibleModa"
        :confirm-loading="confirmLoading"
        width="80%"
        :footer="null"
      >
        <WarehouseCheckModal
          :rowData="rowData2"
          @cancel="visibleModa = false"
          @success="handleSuccess"
        ></WarehouseCheckModal>
      </a-modal>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import printJS from 'print-js';
  import domtoimage from 'dom-to-image';
  import { ref, reactive, watch, onMounted, createVNode } from 'vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import {
    getMesWarehouseCheck,
    deleteMesWarehouseCheck,
    finishMesWarehouseCheck,
    exportMesWarehouseCheck,
  } from '/@/api/mes/warehousecheck';
  import { getWarehouseList, getProductList } from '/@/api/mes/common';
  import SelectUser from '/@/components/Form/src/components/SelectUser.vue';
  import Upload from '/@/components/Form/src/components/Upload.vue';
  import { useModal } from '/@/components/Modal';
  import WarehouseCheckModal from './WarehouseCheckModal.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  let props = defineProps(['rowData']);
  const { t } = useI18n();
  const rowData: {
    id: string;
    isUpdate: boolean;
    flag: string;
  } = reactive({
    id: '',
    isUpdate: false,
    flag: '',
  });

  const baseData1 = ref<any>({});

  const format = ref('YYYY-MM-DD HH:mm:ss');

  const emit = defineEmits(['cancel', 'success']);
  const formRef = ref();
  const storeOptions = ref<any[]>([]);
  const areaOptions = ref<any[]>([]);
  const locationOptions = ref<any[]>([]);
  const projectOptions = ref<any[]>([]);
  onMounted(async () => {
    rowData.id = props.rowData.id;
    rowData.isUpdate = props.rowData.isUpdate;
    rowData.flag = props.rowData.flag;
    console.log('row===', rowData);
    getDetailData();
    storeOptions.value = await getWarehouseList(0, '');
    areaOptions.value = await getWarehouseList(1, '');
    locationOptions.value = await getWarehouseList(2, '');
    projectOptions.value = await getProductList();
  });

  watch(
    () => props.rowData,
    (val) => {
      console.log('监听', val);
      if (val) {
        rowData.id = props.rowData.id;
        rowData.isUpdate = props.rowData.isUpdate;
        rowData.flag = props.rowData.flag;
        getDetailData();
      }
    },
  );
  function handleFinish(record: Recordable) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认结束盘点？提交后库存生效',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        finishMesWarehouseCheck(record.id).then((_) => {
          getDetailData();
          notification.success({
            message: 'Tip',
            description: t('结束盘点成功！'),
          });
        });
      },
      onCancel() {},
    });
  }
  const isView = ref<boolean>(false);
  const titleModa = ref<string>('');
  const visibleModa = ref<boolean>(false);

  const confirmLoading = ref<boolean>(false);
  const rowData2 = ref({});
  function handleEdit() {
    rowData2.value = {
      id: rowData.id,
      isUpdate: true,
    };
    titleModa.value = '编辑盘点';
    isView.value = false;
    visibleModa.value = true;
  }
  const handlePrint = async () => {
    const element: HTMLElement = window.document.querySelector('.info-box')!;
    console.log('print----', element);
    const url = await domtoimage.toPng(element);
    printJS({
      printable: url,
      type: 'image',
      documentTitle: '打印',
    });
  };
  function handleSuccess() {
    getDetailData();
  }
  function handleDelete(record: Recordable) {
    deleteList([rowData.id]);
  }
  const { notification } = useMessage();
  function deleteList(ids) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteMesWarehouseCheck(ids).then((_) => {
          emit('success', null);
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }
  const getDetailData = async () => {
    const data = await getMesWarehouseCheck(rowData.id);
    console.log(data, '上部分信息');
    baseData1.value = data;
  };

  const cancel = () => {
    emit('cancel');
  };

  const success = () => {
    formRef.value
      .validate()
      .then(() => {
        emit('success');
      })
      .catch((error) => {
        console.log('error', error);
      });
  };
  function filterColum(column) {
    return column.filter((o) => {
      return o.show == false ? false : true;
    });
  }
  const columnsProp = {
    mainKey: 'mesWarehouseCheckDetailList',
    columns: [
      {
        key: 'eee3093b6f8e467d936b48efcc69eb29',
        title: '物品ID',
        dataIndex: 'productId',
        componentType: 'Input',
        defaultValue: '',
        show: false,
        componentProps: {
          prestrainField: 'product_id',
        },
      },
      {
        key: 'dd232ffeef5c4a05a500165ae1e824d9',
        title: '物品编码',
        dataIndex: 'productNo',
        componentType: 'Input',
        defaultValue: '',
        show: true,
        componentProps: {
          prestrainField: 'product_no',
        },
      },
      {
        key: '8765f3697a6f4821a6212af437d4f211',
        title: '物品名称',
        dataIndex: 'productName',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'product_name',
        },
      },
      {
        key: '0e8d5f2d2aac4c5797e7688128c72133',
        title: '规格型号',
        dataIndex: 'speModel',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'spe_model',
        },
      },
      {
        key: '83263601af294f8987d360bf7e299391',
        title: '类型',
        dataIndex: 'deType',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'de_type',
        },
      },
      {
        key: 'ee99236b6f094d93bbe296fc882de364',
        title: '单位',
        dataIndex: 'unity',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'unity',
        },
      },
      {
        key: 'ee99236b6f094d93bbe296fc882de364',
        title: '库区',
        dataIndex: 'areaId',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'area_id',
        },
      },
      {
        key: 'ee99236b6f094d93bbe296fc882de364',
        title: '库位',
        dataIndex: 'locationId',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'location_id',
        },
      },
      {
        key: '1a201f7da4d148c8935f10cef6251295',
        title: '系统数量',
        dataIndex: 'sysNum',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'num',
        },
      },
      {
        key: 'e0ddcd8fbd534c9991339ab6ecdcc3a9',
        title: '实际数量',
        dataIndex: 'realNum',
        componentType: 'InputNumber',
      },
      {
        key: 'b5445b462b0e44d399d555bdaf717174',
        title: '盈亏数量',
        dataIndex: 'lostNum',
        componentType: 'InputNumber',
        defaultValue: null,
      },
      {
        key: 'b8a89cfd36024592bd68f19fa51f59ab',
        title: '盘点结果',
        dataIndex: 'checkResult',
        componentType: 'XjrSelect',
        componentProps: {
          width: '100%',
          span: '',
          placeholder: '请选择',
          showLabel: true,
          showSearch: false,
          clearable: false,
          disabled: false,
          staticOptions: [
            { key: 1, label: '正常', value: '1' },
            { key: 2, label: '盘赢', value: '2' },
            { key: 3, label: '盘亏', value: '3' },
          ],
          defaultSelect: '1',
          datasourceType: 'staticData',
          params: null,
          labelField: 'label',
          valueField: 'value',
          apiConfig: {},
          dicOptions: [],
          required: false,
          rules: [],
          events: {},
        },
      },
      {
        key: '45c36907d9a546e4ac6422110bcd995d',
        title: '备注',
        dataIndex: 'remark',
        componentType: 'Input',
        defaultValue: '',
      },
      // { title: '操作', key: 'action', fixed: 'right', width: '50px' },
    ],
    span: '24',
    preloadType: 'api',
    apiConfig: {
      path: '/mes/getMaterialListByCheck',
      method: 'GET',
      apiId: 'copy1691376953075d25524',
      apiParams: [
        {
          key: '1',
          title: 'Query Params',
          tableInfo: [
            {
              name: 'keyword',
              value: null,
              description: null,
              required: false,
              dataType: 'String',
              type: null,
              defaultValue: null,
              validateType: null,
              error: null,
              expression: null,
              children: null,
              bindType: '',
            },
          ],
        },
        { key: '2', title: 'Header', tableInfo: [] },
        { key: '3', title: 'Body' },
      ],
      outputParams: [
        { tableTitle: '物品编码', name: 'product_no' },
        { tableTitle: '物品名称', name: 'product_name' },
        { tableTitle: '规格型号', name: 'spe_model' },
        { tableTitle: '类型', name: 'de_type' },
        { tableTitle: '单位', name: 'unity' },
        { tableTitle: '系统数量', name: 'num' },
      ],
    },
    itemId: '',
    dicOptions: [],
    useSelectButton: true,
    useAddButton: false, //不显示新增按钮
    buttonName: '新增',
    showLabel: true,
    showComponentBorder: true,
    showFormBorder: true,
    showIndex: false,
    multipleHeads: [],
  };
</script>

<style lang="less" scoped>
  .padding {
    padding: 12px;
  }

  .back_color {
    background-color: hsl(0, 0%, 98%);
    position: relative;
  }

  .marginTop {
    margin-top: 12px;
  }
</style>
