<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="outCode" required :labelCol="{ span: 9 }">
            <a-input
              v-model:value="formData.outCode"
              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="outType" required>
            <a-select
              ref="select"
              v-model:value="formData.outType"
              @change="changeType"
              :disabled="!rowData.isUpdate"
            >
              <a-select-option value="1">领用出库</a-select-option>
              <!-- <a-select-option value="2">委外领用</a-select-option> -->
              <a-select-option value="3">销售出库</a-select-option>
              <a-select-option value="4">采购退货出库</a-select-option>
              <a-select-option value="0">其他出库</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-col :span="24">
        <a-form-item label="出库主题" name="outName" :labelCol="{ span: 3 }" required>
          <a-input
            :disabled="!rowData.isUpdate"
            v-model:value="formData.outName"
            placeholder="请输入"
          />
        </a-form-item>
      </a-col>
      <a-row>
        <a-col :span="12">
          <a-form-item label="出库日期" name="outDate" required>
            <XjrDatePicker
              :disabled="!rowData.isUpdate"
              v-model:value="formData.outDate"
              placeholder="请选择"
              :allowClear="true"
              :format="'YYYY-MM-DD'"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.outType == '4'">
          <a-form-item v-show="false" label="采购单号ID" name="buyId" required>
            <a-input v-model:value="formData.buyId" />
          </a-form-item>
          <a-form-item label="采购单号" name="buyNo" required>
            <a-input
              @change="changeType"
              allowClear
              v-model:value="formData.buyNo"
              :disabled="!rowData.isUpdate"
              placeholder="请选择"
              @click="openOrderDialog"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.outType == '1' || formData.outType == '2'">
          <a-form-item v-show="false" label="生产单号ID" name="produceId" required
            ><a-input v-model:value="formData.produceId" />
          </a-form-item>
          <a-form-item label="生产单号" name="produceNo" required>
            <a-input
              @change="changeType"
              allowClear
              v-model:value="formData.produceNo"
              :disabled="!rowData.isUpdate"
              placeholder="请选择"
              @click="openOrderDialog"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.outType == '3'">
          <a-form-item v-show="false" label="销售单号ID" name="saleId" required>
            <a-input v-model:value="formData.saleId" />
          </a-form-item>
          <a-form-item label="销售单号" name="saleNo" required>
            <a-input
              @change="changeType"
              allowClear
              v-model:value="formData.saleNo"
              :disabled="!rowData.isUpdate"
              placeholder="请选择"
              @click="openOrderDialog"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <div v-if="formData.outType == '3'">
        <a-row>
          <a-col :span="12">
            <a-form-item label="客户名称" name="saleCustomer"
              ><a-input v-model:value="formData.saleCustomer" :disabled="true" placeholder="" />
            </a-form-item>
          </a-col>
        </a-row>
      </div>
      <div v-if="formData.outType == '4'">
        <a-row>
          <a-col :span="12">
            <a-form-item v-show="false" label="供应商ID" name="supplierId">
              <a-input v-model:value="formData.supplierId" :disabled="true" placeholder="" />
            </a-form-item>
            <a-form-item label="供应商" name="supplier">
              <a-input v-model:value="formData.supplier" :disabled="true" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系人" name="supplierUser">
              <a-input v-model:value="formData.supplierUser" :disabled="true" placeholder=""
            /></a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="联系电话" name="supplierPhone">
              <a-input v-model:value="formData.supplierPhone" :disabled="true" placeholder=""
            /></a-form-item>
          </a-col>
        </a-row>
      </div>
      <a-row>
        <a-col :span="12">
          <a-form-item label="领用部门" name="recUnit">
            <SelectDepartment
              :size="1"
              v-model:value="formData.recUnit"
              :style="{ width: '100%' }"
              :disabled="!rowData.isUpdate"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="领用人员" name="recUser">
            <SelectUser
              :disabled="!rowData.isUpdate"
              v-model:value="formData.recUser"
              :multiple="false"
              suffix="ant-design:setting-outlined"
              placeholder=""
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <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-col :span="12">
          <a-form-item label="出库操作人员" name="outDouser" required
            ><SelectUser
              :disabled="!rowData.isUpdate"
              v-model:value="formData.outDouser"
              :multiple="false"
              suffix="ant-design:setting-outlined"
              placeholder="请选择"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="关联项目" name="relevancePro">
            <a-select
              :options="projectOptions"
              placeholder="请选择"
              v-model:value="formData.relevancePro"
              :disabled="!rowData.isUpdate"
              allowClear
            >
            </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="multipleDialog = true" 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.mesWarehouseOutDetailList"
      :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 === 'warArea'">
          <a-select
            :options="areaOptions"
            placeholder="请选择"
            v-model:value="record.warArea"
            :disabled="!rowData.isUpdate"
            allowClear
          >
          </a-select>
        </template>
        <template v-if="column.dataIndex === 'locationId'">
          <a-select
            :options="locationOptions[record.warArea]"
            placeholder="请选择"
            v-model:value="record.locationId"
            :disabled="!rowData.isUpdate"
            allowClear
          >
          </a-select>
        </template>
        <template v-if="column.dataIndex === 'batchno'">
          <a-input v-model:value="record.batchno" :disabled="!rowData.isUpdate" placeholder="" />
        </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 === 'produceDate'">
          <XjrDatePicker
            :disabled="!rowData.isUpdate"
            v-model:value="record.produceDate"
            placeholder="请选择"
            :allowClear="true"
            :format="'YYYY-MM-DD'"
            style="width: 100%"
          />
        </template>
        <template v-if="column.dataIndex === 'endDate'">
          <XjrDatePicker
            :disabled="!rowData.isUpdate"
            v-model:value="record.endDate"
            placeholder="请选择"
            :allowClear="true"
            :format="'YYYY-MM-DD'"
            style="width: 100%"
          />
        </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.outFile"
      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>

    <a-modal
      :maskClosable="false"
      :title="orderDialogTitle"
      v-model:visible="orderDialog"
      :width="1000"
      :footer="null"
    >
      <div style="padding-bottom: 50px; min-height: 500px">
        <a-table
          :dataSource="orderListOptions"
          :columns="orderLisColumn"
          :row-selection="{
            selectedRowKeys: selectedKeys,
            onChange: onSelectChange,
            type: 'radio',
          }"
          :scroll="{ x: 1000, y: 500 }"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex == 'products'">
              <a-dropdown v-if="record.products">
                <span>
                  {{ record.products.split(',')[0]?.split(':')[0] }}
                  <DownOutlined />
                </span>
                <template #overlay>
                  <a-menu>
                    <a-menu-item v-for="(item, index) in record.products.split(',')" :key="index">
                      <a href="javascript:;">{{ item }}</a>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
          </template>
        </a-table>
      </div>
      <div class="footerDiv" v-if="rowData.isUpdate">
        <a-button @click="closeOrderDialog">取消</a-button>
        <a-button @click="handleSelectOrder" type="primary" style="margin-left: 12px"
          >确认</a-button
        >
      </div>
    </a-modal>
  </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 {
    addMesWarehouseOut,
    getMesWarehouseOut,
    updateMesWarehouseOut,
  } from '/@/api/mes/warehouseout';
  import {
    getAutoCode,
    getWarehouseList,
    getProductList,
    getBuyOrderList,
    getSaleOrderList,
    getWorkOrderList,
    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 orderDialog = ref<boolean>(false);
  const orderDialogTitle = ref<string>();
  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);
  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>({
    outCode: '',
    isSysNum: '',
    isSysNumBoolean: true,
    mesWarehouseOutDetailList: [],
  });
  const emit = defineEmits(['cancel', 'success']);
  const formRef = ref();

  const { notification } = useMessage();
  const total = ref({
    countSum: 0 as any,
    amountSum: 0 as any,
  });
  const orderListOptions = ref<any[]>([]);
  const orderLisColumn = ref<any[]>([]);
  function onSelectChangeSub(selectedRowKeys: [], selectedRows) {
    selectedKeysSub.value = selectedRowKeys;
    selectedRowsDataSub.value = selectedRows;
  }
  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }
  function closeOrderDialog() {
    orderDialog.value = false;
    selectedRowsData.value = [];
    selectedKeys.value = [];
  }
  async function openOrderDialog() {
    orderListOptions.value = [];
    orderLisColumn.value = [];
    if (formData.value.outType == '4') {
      orderDialogTitle.value = '选择采购订单';
      //采购
      orderLisColumn.value = orderLisColumn.value = [
        {
          dataIndex: 'purchase_number',
          title: '采购订单号',
          bindField: 'buy_no',
          show: true,
          width: 150,
        },
        { dataIndex: 'theme', title: '采购订单主题', bindField: null, show: true, width: 150 },
        {
          dataIndex: 'supplier_name',
          title: '供应商',
          bindField: 'supplier',
          show: true,
          width: 150,
        },
        {
          dataIndex: 'purchase_date',
          title: '采购日期',
          bindField: null,
          show: true,
          width: 150,
        },

        {
          dataIndex: 'count_sum',
          title: '采购数量',
          width: 150,
        },
        // {
        //   dataIndex: 'in_store_count',
        //   title: '入库数量',
        //   width: 150,
        // },
        {
          dataIndex: 'products',
          title: '物品概要',
          width: 150,
          align: 'right',
        },
      ];
      orderListOptions.value = await getBuyOrderList();
    }
    if (formData.value.outType == '1') {
      orderDialogTitle.value = '选择生产订单';
      //生产单，生产退单
      orderLisColumn.value = [
        {
          dataIndex: 'work_no',
          title: '工单编号',
          bindField: 'produce_no',
          show: true,
          width: 150,
        },
        {
          dataIndex: 'material_no',
          title: '产品编码',
          bindField: null,
          show: true,
          width: 150,
        },
        {
          dataIndex: 'material_name',
          title: '产品名称',
          bindField: 'produce_unit',
          show: true,
          width: 150,
        },

        {
          dataIndex: 'plan_num',
          title: '计划产量',
          bindField: '',
          show: true,
          width: 150,
        },
        {
          dataIndex: 'in_store_count',
          title: '入库数量',
          bindField: '',
          show: true,
          width: 150,
        },
        { dataIndex: 'create_date', title: '单据日期', bindField: '', show: true, width: 150 },
        // { dataIndex: 'products', title: '物品概要', bindField: '', show: true, width: 150 },
      ];
      orderListOptions.value = await getWorkOrderList();
    }
    if (formData.value.outType == '3') {
      orderDialogTitle.value = '选择销售订单';
      //销售单
      orderLisColumn.value = [
        {
          dataIndex: 'sale_number',
          title: '销售单号',
          bindField: 'sale_no',
          show: true,
          width: 150,
        },
        { dataIndex: 'theme', title: '销售订单主题', bindField: '', show: true, width: 150 },
        {
          dataIndex: 'customer_name',
          title: '客户姓名',
          bindField: 'sale_customer',
          show: true,
          width: 150,
        },
        { dataIndex: 'sale_date', title: '销售日期', bindField: '', show: true, width: 150 },
        {
          dataIndex: 'in_store_state',
          title: '入库状态',
          bindField: '',
          show: true,
          width: 150,
        },
        { dataIndex: 'products', title: '物品概要', align: 'right', show: true, width: 150 },
      ];
      orderListOptions.value = await getSaleOrderList();
    }
    orderDialog.value = true;
  }
  function handleSelectOrder() {
    //弹层选择数据回显
    console.log('selectedRowsData', selectedRowsData.value);
    selectedRowsData.value.forEach((ele) => {
      if (formData.value.outType == '4') {
        formData.value.buyId = ele.id;
        formData.value.buyNo = ele.purchase_number;
        formData.value.supplierId = ele.supplier_id;
        formData.value.supplier = ele.supplier_name;
        formData.value.supplierUser = ele.supplier_person;
        formData.value.supplierPhone = ele.purchase_phone;
        formData.value.buyUnit = ele.purchase_dept_id;
        formData.value.buyUser = ele.purchase_person_id;
      }
      if (formData.value.outType == '1') {
        formData.value.produceId = ele.id;
        formData.value.produceNo = ele.work_no;
      }
      if (formData.value.outType == '2') {
        formData.value.produceId = ele.id;
        formData.value.produceNo = ele.work_no;
      }
      if (formData.value.outType == '3') {
        formData.value.saleId = ele.id;
        formData.value.saleNo = ele.sale_number;
        formData.value.saleCustomer = ele.customer_name;
        formData.value.saleManager = ele.manager;
        formData.value.saleUser = ele.client_person;
        formData.value.salePhone = ele.phone;
        formData.value.saleUnit = ele.dep_name;
      }
    });
    closeOrderDialog();
    changeType('');
  }
  function changeType(init) {
    if (init != '1') formData.value.mesWarehouseOutDetailList = [];
    //1采购出库、2生产单出库、3委外加'putIn'           工出库、4生产退料出库、5销售退货出库0-其他出库
    console.log('formData.value', formData.value);
    columnsProp.apiConfig.path =
      '/mes/getOutStoreMaterialList?queryType=' +
      formData.value.outType +
      '&purchase_id=' +
      formData.value.buyId +
      '&prowork_id=' +
      formData.value.workorderId +
      '&proorder_id=' +
      formData.value.produceId +
      '&sale_id=' +
      formData.value.saleId +
      '&warehouse_id=' +
      formData.value.outStorage;
    //控制物品表格字段：
    columnsProp.columns.forEach((ele) => {
      if (ele.dataIndex == 'batchno') {
        if (formData.value.outType == '1') ele.show = false;
        else ele.show = true;
      }
      // if (ele.dataIndex == 'num') {
      //   if (formData.value.outType == '4') ele.title = '采购数量';
      //   if (formData.value.outType == '1') ele.title = '计划生产';
      //   if (formData.value.outType == '2') ele.title = '计划生产';
      //   if (formData.value.outType == '3') ele.title = '销售数量';
      //   if (formData.value.outType == '0') ele.show = false;
      //   else ele.show = true;
      // }
      // if (ele.dataIndex == 'hasIn' || ele.dataIndex == 'totalPrice') {
      //   if (formData.value.outType == '0') ele.show = false;
      //   else ele.show = true;
      // }
    });

    //控制物品弹层字段

    if (formData.value.outType == '0') {
      columnsProp.apiConfig.outputParams = [
        { tableTitle: '物品编码', name: 'material_no' },
        { tableTitle: '物品名称', name: 'material_name' },
        { tableTitle: '规格型号', name: 'model' },
        { tableTitle: '单位', name: 'unity' },
        { tableTitle: '库存', name: 'num' },
        // { tableTitle: '单价', name: 'price' },
        // { tableTitle: '数量', name: 'num' },
        // { tableTitle: '合计金额', name: 'total_price' },
        // { tableTitle: '已入库', name: 'in_store_count' },
        // { tableTitle: '未入库', name: 'no_in_store_count' },
      ];
    } else {
      columnsProp.apiConfig.outputParams = [
        { tableTitle: '物品编码', name: 'material_no' },
        { tableTitle: '物品名称', name: 'material_name' },
        { tableTitle: '规格型号', name: 'model' },
        { tableTitle: '单位', name: 'unity' },
        // { tableTitle: '品牌', name: '' },
        { tableTitle: '单价', name: 'price' },
        { tableTitle: '数量', name: 'num' },
        { tableTitle: '合计金额', name: 'total_price' },
        { tableTitle: '已入库', name: 'in_store_count' },
        { tableTitle: '未入库', name: 'no_in_store_count' },
      ];
    }
  }
  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.mesWarehouseOutDetailList = formData.value.mesWarehouseOutDetailList.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.outCode = await getAutoCode('mesoutWarehouseNo');
      formData.value.isSysNum = '1';
    } else {
      formData.value.outCode = '';
      formData.value.isSysNum = '';
    }
  }
  async function changeStorage() {
    areaOptions.value = await getWarehouseAreaTreeList(formData.value.outStorage);
    areaOptions.value?.forEach(async (ele) => {
      locationOptions[ele.value] = ele.children;
    });
    changeType('');
  }
  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.outDate = currentDate();
      const userStore = useUserStore();
      formData.value.outDouser = userStore?.getUserInfo?.id;
      handleSysChange();
      handleTotalChange();
    } else {
      const res = await getMesWarehouseOut(rowData.id);
      formData.value = res;
      formData.value.isSysNumBoolean = formData.value.isSysNum == '1' ? true : false;
      if (!formData.value.mesWarehouseOutDetailList) formData.value.mesWarehouseOutDetailList = [];
      else
        formData.value.mesWarehouseOutDetailList.forEach((e, index) => {
          e.key = index;
        });
      changeStorage();
      changeType('1');
      handleTotalChange();
    }
  };

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

    formData.value.mesWarehouseOutDetailList.map((item) => {
      const price = item.price || 0;
      const count = parseInt(item.num) || 0;
      unref(total).countSum += count;
      unref(total).amountSum += count * price;
      item.totalPrice = 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.outFile = formData.value.outFile;
      values.state = state;
      values.isSysNum = formData.value.isSysNumBoolean ? '1' : '';
      values.outNum = unref(total).countSum;
      values.outPrice = unref(total).amountSum;
      if (
        !formData.value.mesWarehouseOutDetailList ||
        formData.value.mesWarehouseOutDetailList.length == 0
      ) {
        notification.error({
          message: 'Tip',
          description: t('请新增物品明细'),
        });
        return;
      }
      values.mesWarehouseOutDetailList = formData.value.mesWarehouseOutDetailList;
      console.log('values', values, formData.value);

      // TODO custom api
      if (!values.id) {
        //false 新增
        await addMesWarehouseOut(values);
        notification.success({
          message: 'Tip',
          description: t('新增出库成功！'),
        }); //提示消息
      } else {
        await updateMesWarehouseOut(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) => {
    // formData.value.mesWarehouseOutDetailList = [];
    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;
      formData.value.mesWarehouseOutDetailList.push(dataObj);
    });
  };
  const removeList = (index) => {
    formData.value.mesWarehouseOutDetailList.splice(index, 1);
  };
  const columnsProp = {
    mainKey: 'mesWarehouseOutDetailList',
    columns: [
      {
        key: '80beb877368c4bebb3d52ad1af2b9b0a',
        title: '数据来源',
        dataIndex: 'sourceId',
        componentType: 'Input',
        defaultValue: '',
        show: false,
        componentProps: {
          prestrainField: 'id',
        },
      },
      {
        key: '5707278f9ac94a95b1d74eebcc135bb9',
        title: '物品ID',
        dataIndex: 'productId',
        componentType: 'Input',
        defaultValue: '',
        show: false,
        componentProps: {
          prestrainField: 'material_id',
        },
      },
      {
        key: '8ca9bdf071af4d089a8a990dd6cfe38b',
        title: '物品编码',
        dataIndex: 'productNo',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'material_no',
        },
      },
      {
        key: '5b123250db4148e8b197a2191e32dc81',
        title: '物品名称',
        dataIndex: 'productName',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'material_name',
        },
      },
      {
        key: 'eaf6f3cf87e34e89bb26281324083b6e',
        title: '规格型号',
        dataIndex: 'speModel',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'model',
        },
      },
      {
        key: 'a49380a4287f48dbb7ac3f631799d1c3',
        title: '单位',
        dataIndex: 'unity',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'unity',
        },
      },
      {
        key: 'e3b47a95d51e4094ac36cd0b0c4c026e',
        title: '库区',
        dataIndex: 'warArea',
        componentType: 'XjrSelect',
        componentProps: {
          prestrainField: 'area_id',
        },
      },
      {
        key: '1c57e1d028144826bfe6f384f4591ddc',
        title: '库位',
        dataIndex: 'locationId',
        componentType: 'XjrSelect',
        componentProps: {
          prestrainField: 'location_id',
        },
      },
      {
        key: '4a28e1b55de84c6ab1f2ad2e6ab2f5d9',
        title: '批次号',
        dataIndex: 'batchno',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: '',
        },
      },
      {
        key: '321aeb8b88a5424c8f6f2a8a0b3e9c55',
        title: '系统数量',
        dataIndex: 'sysNum',
        componentType: 'InputNumber',
        show: false,
        componentProps: {
          prestrainField: 'num',
        },
      },
      {
        key: '321aeb8b88a5424c8f6f2a8a0b3e9c55',
        title: '出库数量',
        dataIndex: 'num',
        componentType: 'InputNumber',
        defaultValue: null,
        componentProps: {
          prestrainField: '',
        },
      },
      {
        key: '95a5ede565fa480e8e3f955e55245300',
        title: '单价',
        dataIndex: 'price',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'price',
        },
      },
      {
        key: '0f4795654f6c412abe604382d0fc7413',
        title: '合计',
        dataIndex: 'totalPrice',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'total_price',
        },
      },
      {
        key: 'f520f562c4d84e2f9972f854badbbbe6',
        title: '生产日期',
        dataIndex: 'produceDate',
        componentType: 'DatePicker',
        defaultValue: '',
        componentProps: {},
      },
      {
        key: '25c42598620f4f8fb89757b12eea9b40',
        title: '到期日期',
        dataIndex: 'endDate',
        componentType: 'DatePicker',
        defaultValue: '',
        componentProps: {},
      },
      {
        key: '99510f3b8c6b429ca3c3e748a1c0b14a',
        title: '备注',
        dataIndex: 'remark',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: '',
        },
      },
      // { title: '操作', key: 'action', fixed: 'right', width: '50px' },
    ],
    span: '24',
    preloadType: 'api',
    apiConfig: {
      path: '/mes/getOutStoreMaterialList',
      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: '',
            },
            {
              name: 'purchase_id',
              value: 'buy_no',
              description: '采购订单id',
              required: false,
              dataType: 'String',
              type: null,
              defaultValue: null,
              validateType: null,
              error: null,
              expression: null,
              children: null,
              bindType: 'data',
            },
            {
              name: 'showLabel',
              value: '',
              description: '回显字段',
              required: false,
              dataType: 'String',
              type: null,
              defaultValue: 'code',
              validateType: null,
              error: null,
              expression: null,
              children: null,
              bindType: '',
            },
            {
              name: 'queryType',
              value: 'out_type',
              description: '查询类型：1-采购',
              required: false,
              dataType: null,
              type: null,
              defaultValue: null,
              validateType: null,
              error: null,
              expression: null,
              children: null,
              bindType: 'data',
            },
          ],
        },
        { key: '2', title: 'Header', tableInfo: [] },
        { key: '3', title: 'Body' },
      ],
      script:
        'var condition=" and purchase_id=#{purchase_id}";\r\n// if(purchase_id!=null&&purchase_id!=""){ \r\n//     condition+=" and purchase_id=#{purchase_id}";\r\n// }\r\nreturn db.select("SELECT id AS `key` ,id AS `value`,CODE AS label,t.*,t.price*t.count as total_price,t.price*t.return_count as out_total_price FROM case_erp_purchase_detail t WHERE 1=1  "+condition)',
      outputParams: [
        { tableTitle: '物品编码', name: 'code' },
        { tableTitle: '物品名称', name: 'name' },
        { tableTitle: '规格型号', name: 'model' },
        { tableTitle: '单位', name: 'unit_name' },
        { tableTitle: '单价', name: 'price' },
        { tableTitle: '数量', name: 'count' },
        { tableTitle: '合计金额', name: 'total_price' },
        { tableTitle: '已入库', name: 'in_store_count' },
        { tableTitle: '未入库', name: 'no_in_store_count' },
        {},
        {},
      ],
    },
    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>
