<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-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="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-col :span="12">
          <a-form-item label="申请部门" name="dataUnit" required>
            <SelectDepartment
              :size="1"
              v-model:value="formData.dataUnit"
              :style="{ width: '100%' }"
              :disabled="!rowData.isUpdate"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <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-col :span="12">
          <a-form-item label="联系电话" name="dataPhone" required>
            <a-input
              :disabled="!rowData.isUpdate"
              v-model:value="formData.dataPhone"
              placeholder="请输入"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="调入仓库" name="inStorage" required>
            <a-select
              :options="storeOptions"
              placeholder="请选择"
              v-model:value="formData.inStorage"
              :disabled="!rowData.isUpdate"
              allowClear
              @change="changeInStorage"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="调出仓库" name="outStorage" required>
            <a-select
              :options="storeOptions"
              placeholder="请选择"
              v-model:value="formData.outStorage"
              :disabled="!rowData.isUpdate"
              allowClear
              @change="changeStorage"
            >
            </a-select>
          </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.mesWarehouseChgapplyDetailList"
      :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 === 'outAreaId'">
          <a-select
            :options="areaOptions"
            placeholder="请选择"
            v-model:value="record.outAreaId"
            :disabled="true"
            allowClear
          >
          </a-select>
        </template>
        <template v-if="column.dataIndex === 'outLocationId'">
          <a-select
            :options="locationOptions[record.outAreaId]"
            placeholder="请选择"
            v-model:value="record.outLocationId"
            :disabled="true"
            allowClear
          >
          </a-select>
        </template>
        <template v-if="column.dataIndex === 'inAreaId'">
          <a-select
            :options="inareaOptions"
            placeholder="请选择"
            v-model:value="record.inAreaId"
            :disabled="!rowData.isUpdate"
            allowClear
          >
          </a-select>
        </template>
        <template v-if="column.dataIndex === 'inLocationId'">
          <a-select
            :options="inlocationOptions[record.inAreaId]"
            placeholder="请选择"
            v-model:value="record.inLocationId"
            :disabled="!rowData.isUpdate"
            allowClear
          >
          </a-select>
        </template>
        <template v-if="column.dataIndex === 'num'">
          <a-input-number
            :min="0"
            :max="record.sysNum"
            :step="1"
            :disabled="!rowData.isUpdate"
            v-model:value="record.num"
            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 {
    addMesWarehouseChgapply,
    getMesWarehouseChgapply,
    updateMesWarehouseChgapply,
  } from '/@/api/mes/warehousechgapp';
  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,
    mesWarehouseChgapplyDetailList: [],
  });
  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.mesWarehouseChgapplyDetailList =
      formData.value.mesWarehouseChgapplyDetailList.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('meswarehouseChgApplyNo');
      formData.value.isSysNum = '1';
    } else {
      formData.value.dataCode = '';
      formData.value.isSysNum = '';
    }
  }
  async function changeStorage() {
    columnsProp.apiConfig.path =
      '/mes/getMesWarehouseStockList?queryType=chg&warehouse_id=' + formData.value.outStorage;
    areaOptions.value = await getWarehouseAreaTreeList(formData.value.outStorage);
    areaOptions.value?.forEach(async (ele) => {
      locationOptions[ele.value] = ele.children;
    });
  }
  async function changeInStorage() {
    inareaOptions.value = await getWarehouseAreaTreeList(formData.value.inStorage);
    inareaOptions.value?.forEach(async (ele) => {
      inlocationOptions[ele.value] = ele.children;
    });
  }
  function openMultipleDialog() {
    if (!formData.value.outStorage || formData.value.outStorage.length == 0) {
      notification.error({
        message: 'Tip',
        description: t('请先选择调出仓库'),
      });
      return;
    }
    multipleDialog.value = true;
  }
  const storeOptions = ref<any[]>([]);
  const areaOptions = ref<any[]>([]);
  const inareaOptions = ref<any[]>([]);
  const locationOptions = {};
  const inlocationOptions = {};
  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;
      formData.value.dataPhone = userStore?.getUserInfo?.mobile;

      handleSysChange();
      handleTotalChange();
    } else {
      const res = await getMesWarehouseChgapply(rowData.id);
      formData.value = res;
      formData.value.isSysNumBoolean = formData.value.isSysNum == '1' ? true : false;
      if (!formData.value.mesWarehouseChgapplyDetailList)
        formData.value.mesWarehouseChgapplyDetailList = [];
      else
        formData.value.mesWarehouseChgapplyDetailList.forEach((e, index) => {
          e.key = index;
        });
      changeStorage();
      changeInStorage();
      handleTotalChange();
    }
  };

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

    formData.value.mesWarehouseChgapplyDetailList.map((item) => {
      const price = item.price || 0;
      const count = parseInt(item.num) || 0;

      unref(total).countSum += count;
      unref(total).amountSum += count * price;
    });
    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.mesWarehouseChgapplyDetailList ||
        formData.value.mesWarehouseChgapplyDetailList.length == 0
      ) {
        notification.error({
          message: 'Tip',
          description: t('请新增物品明细'),
        });
        return;
      }
      values.mesWarehouseChgapplyDetailList = formData.value.mesWarehouseChgapplyDetailList;
      console.log('values', values, formData.value);

      // TODO custom api
      if (!values.id) {
        //false 新增
        await addMesWarehouseChgapply(values);
        notification.success({
          message: 'Tip',
          description: t('新增盘点成功！'),
        }); //提示消息
      } else {
        await updateMesWarehouseChgapply(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.mesWarehouseChgapplyDetailList = [];
    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.mesWarehouseChgapplyDetailList)
        formData.value.mesWarehouseChgapplyDetailList = [];
      formData.value.mesWarehouseChgapplyDetailList.push(dataObj);
    });
  };
  const removeList = (index) => {
    formData.value.mesWarehouseChgapplyDetailList.splice(index, 1);
  };
  const columnsProp = {
    mainKey: 'mesWarehouseChgapplyDetailList',
    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: 'outAreaId',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'area_id',
        },
      },
      {
        key: 'ee99236b6f094d93bbe296fc882de364',
        title: '出库库位',
        dataIndex: 'outLocationId',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'location_id',
        },
      },
      {
        key: 'ee99236b6f094d93bbe296fc882de364',
        title: '入库库区',
        dataIndex: 'inAreaId',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: '',
        },
      },
      {
        key: 'ee99236b6f094d93bbe296fc882de364',
        title: '入库库位',
        dataIndex: 'inLocationId',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: '',
        },
      },
      {
        key: '1a201f7da4d148c8935f10cef6251295',
        title: '系统数量',
        dataIndex: 'sysNum',
        componentType: 'Input',
        defaultValue: '',
        show: false,
        componentProps: {
          prestrainField: 'num',
        },
      },
      {
        key: '1a201f7da4d148c8935f10cef6251295',
        title: '调拨数量',
        dataIndex: 'num',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          // prestrainField: 'num',
        },
      },

      {
        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>
