<template>
  <div class="padding" style="height: 700px; overflow: auto">
    <div class="sub-title">基础信息</div>
    <a-form ref="formRef" :model="formData" :labelCol="{ span: 6 }">
      <a-row>
        <a-col :span="8">
          <a-form-item label="盘点编号" name="dataCode" required :labelCol="{ span: 9 }">
            <a-input
              v-model:value="formData.dataCode"
              placeholder="请输入编码"
              :readonly="formData.isSysNum == '1' || formData.id?.length > 0"
              :disabled="!rowData.isUpdate"
            />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="" name="isSysNum">
            <a-checkbox
              :disabled="!rowData.isUpdate || formData.id?.length > 0"
              v-model:checked="formData.isSysNumBoolean"
              @change="handleSysChange"
            >
              用系统编号
            </a-checkbox>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="盘点日期" name="dataDate" required>
            <XjrDatePicker
              :disabled="!rowData.isUpdate"
              v-model:value="formData.dataDate"
              placeholder="请选择"
              :allowClear="true"
              :format="'YYYY-MM-DD'"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-col :span="24">
        <a-form-item label="盘点主题" name="dataName" :labelCol="{ span: 3 }" required>
          <a-input
            :disabled="!rowData.isUpdate"
            v-model:value="formData.dataName"
            placeholder="请输入"
          />
        </a-form-item>
      </a-col>

      <a-row>
        <a-col :span="12">
          <a-form-item label="盘点仓库" name="dataStorage" required>
            <a-select
              :options="storeOptions"
              placeholder="请选择"
              v-model:value="formData.dataStorage"
              :disabled="!rowData.isUpdate"
              allowClear
              @change="changeStorage"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="盘点人员" name="dataUser" required
            ><SelectUser
              :disabled="!rowData.isUpdate"
              v-model:value="formData.dataUser"
              :multiple="false"
              suffix="ant-design:setting-outlined"
              placeholder="请选择"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-col :span="24">
        <a-form-item label="备注" name="remark" :labelCol="{ span: 3 }">
          <a-textarea
            :disabled="!rowData.isUpdate"
            v-model:value="formData.remark"
            placeholder="请输入"
            :auto-size="{ minRows: 2, maxRows: 5 }"
          />
        </a-form-item>
      </a-col>
    </a-form>

    <div class="sub-title">物品明细</div>

    <div style="float: right; display: flex" v-if="rowData.isUpdate">
      <a-button type="primary" @click="openMultipleDialog" class="select-btn">添加 </a-button>
      <div style="width: 10px"></div>
      <a-button type="primary" danger @click="handleDelete"> 移除</a-button>
    </div>
    <a-table
      :columns="filterColum(columnsProp.columns)"
      :bordered="true"
      :pagination="false"
      :data-source="formData.mesWarehouseCheckDetailList"
      :scroll="{ x: 'max-content' }"
      :row-selection="{
        selectedRowKeys: selectedKeysSub,
        onChange: onSelectChangeSub,
      }"
      :row-key="(record) => record.key"
    >
      <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.key == 'action'">
          <a title="删除" @click="removeList(index)" v-if="rowData.isUpdate">
            <MinusCircleOutlined style="padding-bottom: 20px" />
          </a>
        </template> -->
        <template v-if="column.dataIndex === 'areaId'">
          <a-select
            :options="areaOptions"
            placeholder="请选择"
            v-model:value="record.areaId"
            :disabled="!rowData.isUpdate"
            allowClear
          >
          </a-select>
        </template>
        <template v-if="column.dataIndex === 'locationId'">
          <a-select
            :options="locationOptions[record.areaId]"
            placeholder="请选择"
            v-model:value="record.locationId"
            :disabled="!rowData.isUpdate"
            allowClear
          >
          </a-select>
        </template>
        <template v-if="column.dataIndex === 'realNum'">
          <a-input-number
            :min="0"
            :step="1"
            :disabled="!rowData.isUpdate"
            v-model:value="record.realNum"
            placeholder="请输入"
            @change="handleTotalChange"
          />
        </template>

        <template v-if="column.dataIndex === 'remark'">
          <a-input v-model:value="record.remark" placeholder="" :disabled="!rowData.isUpdate" />
        </template>
        <!-- <template v-if="column.dataIndex === 'imgFile'">
          <Upload v-model:value="record.imgFile" listType="picture" />
        </template> -->
      </template>
    </a-table>
    <MultipleSelect
      v-if="multipleDialog"
      ref="MultipleSelectRef"
      v-model:multipleDialog="multipleDialog"
      :params="{ itemId }"
      :datasourceType="columnsProp.preloadType"
      :dicOptions="columnsProp.dicOptions"
      :apiConfig="columnsProp.apiConfig"
      :isSubFormUse="true"
      @submit="renderSubFormList"
      popupType="preload"
    />
    <div class="table-bottom">
      <span>合计</span>
      <div>
        <span>
          总量：
          <span class="price">{{ total.countSum }}</span>
        </span>
        <!-- <span>
          总金额：
          <span class="price">{{ total.amountSum }}</span>
        </span> -->
      </div>
    </div>
    <div class="sub-title">附件</div>
    <Upload
      :disabled="!rowData.isUpdate"
      v-model:value="formData.dataFile"
      listType="dragger"
      tip="支持扩展名：.doc  .docx  .pdf  .jpg ..."
      :style="{ width: '200px' }"
    />
    <a-divider />
    <div class="footerDiv" v-if="rowData.isUpdate">
      <a-button @click="handleClose">取消</a-button>
      <a-button @click="handleSubmit(0)" type="primary" style="margin-left: 12px">暂存</a-button>
      <a-button @click="handleSubmitConfirm(1)" type="primary" style="margin-left: 12px"
        >确认</a-button
      >
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, computed, unref, watch, onMounted } from 'vue';
  import { Modal } from 'ant-design-vue';
  import { DownOutlined, UpOutlined } from '@ant-design/icons-vue';
  import Upload from '/@/components/Form/src/components/Upload.vue';
  import SelectModal from './SelectModal.vue';
  import SelectUser from '/@/components/Form/src/components/SelectUser.vue';
  import SelectDepartment from '/@/components/Form/src/components/SelectDepartment.vue';
  import { XjrDatePicker } from '/@/components/DatePicker';

  import AutoCodeRule from '/@/components/Form/src/components/AutoCodeRule.vue';
  import { MultipleSelect } from '/@/components/MultiplePopup';
  import { getSaleCode } from '/@/api/erp/sale/order';

  import {
    addMesWarehouseCheck,
    getMesWarehouseCheck,
    updateMesWarehouseCheck,
  } from '/@/api/mes/warehousecheck';
  import {
    getAutoCode,
    getWarehouseList,
    getProductList,
    getWarehouseAreaTreeList,
  } from '/@/api/mes/common';
  import { getUser } from '/@/api/system/user';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  let props = defineProps(['rowData']);
  const { t } = useI18n();
  const selectedKeysSub = ref<string[]>([]);
  const selectedRowsDataSub = ref<any[]>([]);
  const rowData: {
    id: string;
    isUpdate: boolean;
    flag: string;
  } = reactive({
    id: '',
    isUpdate: false,
    flag: '',
  });
  const formData = ref<any>({
    dataCode: '',
    isSysNum: '',
    isSysNumBoolean: true,
    mesWarehouseCheckDetailList: [],
  });
  const emit = defineEmits(['cancel', 'success']);
  const formRef = ref();

  const { notification } = useMessage();
  const total = ref({
    countSum: 0 as any,
    amountSum: 0 as any,
  });
  function onSelectChangeSub(selectedRowKeys: [], selectedRows) {
    selectedKeysSub.value = selectedRowKeys;
    selectedRowsDataSub.value = selectedRows;
  }

  const handleNumberChange = (record) => {
    const price = record.price || 0;
    const count = record.count || 0;
    const discount = record.discount || 0;
    const taxRate = record.taxRate || 0;
    if (discount) {
      record.taxBreak = price * count * (1 - discount / 100) * (taxRate / 100);
    } else {
      record.taxBreak = price * count * (taxRate / 100);
    }
    record.afterTaxAmount = price * count * (1 - discount / 100) + record.taxBreak;
    record.taxBreak = record.taxBreak.toFixed(2);
    record.afterTaxAmount = record.afterTaxAmount.toFixed(2);

    handleTotalChange();
  };

  const handleDelete = () => {
    formData.value.mesWarehouseCheckDetailList = formData.value.mesWarehouseCheckDetailList.filter(
      (x) => !selectedKeysSub.value.includes(x.key),
    );
    handleTotalChange();
  };
  async function handleSysChange() {
    console.log('chg===', rowData, formData, formData.value.isSysNumBoolean);
    if (!rowData.isUpdate) return;

    if (formData.value.isSysNumBoolean) {
      formData.value.dataCode = await getAutoCode('meswarehouseCheckNo');
      formData.value.isSysNum = '1';
    } else {
      formData.value.dataCode = '';
      formData.value.isSysNum = '';
    }
  }
  async function changeStorage() {
    columnsProp.apiConfig.path =
      '/mes/getMaterialListByCheck?warehouse_id=' + formData.value.dataStorage;
    areaOptions.value = await getWarehouseAreaTreeList(formData.value.dataStorage);
    areaOptions.value?.forEach(async (ele) => {
      locationOptions[ele.value] = ele.children;
    });
  }
  function openMultipleDialog() {
    if (!formData.value.dataStorage || formData.value.dataStorage.length == 0) {
      notification.error({
        message: 'Tip',
        description: t('请先选择盘点仓库'),
      });
      return;
    }
    multipleDialog.value = true;
  }
  const storeOptions = ref<any[]>([]);
  const areaOptions = ref<any[]>([]);
  const locationOptions = {};
  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, '');
    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();
      }
    },
  );
  const currentDate = () => {
    return (
      new Date().getFullYear() +
      '-' +
      (new Date().getMonth() + 1 < 10
        ? '0' + (new Date().getMonth() + 1)
        : new Date().getMonth() + 1) +
      '-' +
      (new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate())
    );
  };
  const getDetailData = async () => {
    if (!rowData.id) {
      formData.value = {};
      formData.value.isSysNum = '1';
      formData.value.isSysNumBoolean = true;
      formData.value.dataDate = currentDate();
      const userStore = useUserStore();
      formData.value.dataUser = userStore?.getUserInfo?.id;
      handleSysChange();
      handleTotalChange();
    } else {
      const res = await getMesWarehouseCheck(rowData.id);
      formData.value = res;
      formData.value.isSysNumBoolean = formData.value.isSysNum == '1' ? true : false;
      if (!formData.value.mesWarehouseCheckDetailList)
        formData.value.mesWarehouseCheckDetailList = [];
      else
        formData.value.mesWarehouseCheckDetailList.forEach((e, index) => {
          e.key = index;
        });
      changeStorage();
      handleTotalChange();
    }
  };

  const handleTotalChange = () => {
    unref(total).countSum = 0;
    unref(total).amountSum = 0;

    formData.value.mesWarehouseCheckDetailList.map((item) => {
      const price = item.price || 0;
      const count = parseInt(item.realNum) || 0;
      const sysNum = parseInt(item.sysNum) || 0;
      unref(total).countSum += count;
      unref(total).amountSum += count * price;
      const lostNum = count - sysNum;
      item.lostNum = lostNum; //盈亏数量
      item.checkResult = lostNum == 0 ? '正常' : lostNum > 0 ? '盘赢' : '盘亏'; //盘点结果
    });
    unref(total).amountSum = unref(total).amountSum.toFixed(2);
  };
  async function handleSubmitConfirm(state) {
    await formRef.value?.validate();
    Modal.confirm({
      title: '提示信息',
      content: '是否确认提交？提交后库存生效',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        handleSubmit(state);
      },
      onCancel() {},
    });
  }
  async function handleSubmit(state) {
    try {
      let values = await formRef.value?.validate();
      values.id = formData.value.id;
      values.isSysNum = formData.value.isSysNumBoolean ? '1' : '';
      values.dataFile = formData.value.dataFile;
      values.state = state;
      values.dataNum = unref(total).countSum;
      values.dataPrice = unref(total).amountSum;
      if (
        !formData.value.mesWarehouseCheckDetailList ||
        formData.value.mesWarehouseCheckDetailList.length == 0
      ) {
        notification.error({
          message: 'Tip',
          description: t('请新增物品明细'),
        });
        return;
      }
      values.mesWarehouseCheckDetailList = formData.value.mesWarehouseCheckDetailList;
      console.log('values', values, formData.value);

      // TODO custom api
      if (!values.id) {
        //false 新增
        await addMesWarehouseCheck(values);
        notification.success({
          message: 'Tip',
          description: t('新增盘点成功！'),
        }); //提示消息
      } else {
        await updateMesWarehouseCheck(values);
        notification.success({
          message: 'Tip',
          description: t('修改盘点成功！'),
        }); //提示消息
      }
      // formRef.value.resetFields();
      emit('success');
    } finally {
    }
  }

  function handleClose() {
    emit('cancel');
  }

  const multipleDialog = ref<boolean>(false);
  function filterColum(column) {
    return column.filter((o) => {
      return o.show == false ? false : true;
    });
  }
  const renderSubFormList = async (list) => {
    console.log('明细选择', list);
    // formData.value.mesWarehouseCheckDetailList = [];
    list?.forEach((x, i) => {
      const dataObj = {};
      columnsProp.columns?.map((item) => {
        if (!item?.dataIndex) return;
        dataObj[item.dataIndex as string] = item.componentProps?.prestrainField
          ? x[item.componentProps.prestrainField]
          : null;
      });
      dataObj['key'] = new Date().getTime() + '' + i;
      if (!formData.value.mesWarehouseCheckDetailList)
        formData.value.mesWarehouseCheckDetailList = [];
      formData.value.mesWarehouseCheckDetailList.push(dataObj);
    });
  };
  const removeList = (index) => {
    formData.value.mesWarehouseCheckDetailList.splice(index, 1);
  };
  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>
  .sub-title {
    font-weight: bold;
    margin: 15px 0 20px 3px;
    color: #606266;
  }

  .table-bottom {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #ddd;
    padding: 5px;

    & > div > span {
      margin-left: 40px;
    }
  }

  .price {
    color: #f00;
  }
  .footerDiv {
    padding: 10px 16px;
    text-align: right;
    background: white;
    border-top: 1px solid rgb(240, 240, 240);
    border-radius: 0px 0px 2px 2px;
    position: absolute;
    bottom: 1px;
    width: 98%;
  }

  .padding {
    padding: 12px;
  }
</style>
