<template>
  <div class="padding" style="height: 700px; overflow: auto">
    <div class="padding">
      <div style="font-weight: bold; font-size: 16px">基础信息</div>
      <div v-if="baseData1">
        <div class="back_color padding marginTop">
          <a-descriptions title="" :column="2">
            <a-descriptions-item label="工单编号">{{ baseData1.workNo }}</a-descriptions-item>
            <a-descriptions-item label=""></a-descriptions-item>

            <a-descriptions-item label="任务总量">{{ baseData1.taskNum }}</a-descriptions-item>
            <a-descriptions-item label="已派数量">{{ baseData1.sendNum }}</a-descriptions-item>

            <a-descriptions-item label="工序编码">{{ baseData1.stepNo }}</a-descriptions-item>
            <a-descriptions-item label="工序名称">{{ baseData1.stepName }}</a-descriptions-item>
          </a-descriptions>
        </div>
      </div>
    </div>

    <div class="padding">
      <div style="display: flex; justify-content: space-between">
        <div style="font-weight: bold; font-size: 16px">派工操作</div>
        <div>
          <a-button
            v-if="rowData.isUpdate"
            @click="createRow"
            type="primary"
            style="margin-left: 12px"
            >添加</a-button
          >
          <a-button
            v-if="rowData.isUpdate"
            @click="removeRow"
            type="primary"
            style="margin-left: 12px"
            >移除</a-button
          >
        </div>
      </div>
      <a-table
        :columns="filterColum(columnsProp.columns)"
        :bordered="true"
        :pagination="true"
        :data-source="detailList"
        :scroll="{ y: '300px' }"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          type: 'checkbox',
        }"
      >
        <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 === 'sendUser'">
            <SelectUser
              :disabled="!rowData.isUpdate"
              :multiple="false"
              v-model:value="record.sendUser"
              suffix="ant-design:setting-outlined"
              placeholder="请选择"
            />
          </template>
          <template v-if="column.dataIndex === 'sendNum'">
            <a-input-number
              :min="0"
              :step="1"
              :max="baseData1.taskNum"
              :disabled="!rowData.isUpdate"
              v-model:value="record.sendNum"
              @change="chgSendNum"
              style="width: 100%"
              placeholder="请输入"
            />
          </template>
        </template>
      </a-table>
    </div>
    <a-divider />
    <div
      style="
        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%;
      "
      v-if="rowData.isUpdate"
    >
      <a-button @click="handleClose">取消</a-button>
      <a-button @click="handleSubmit" type="primary" style="margin-left: 12px">确认</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { uploadApi } from '/@/api/sys/upload';
  import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
  import { ref, reactive, watch, onMounted, createVNode } from 'vue';
  // import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { getProcessTechList, getWorkOrderStepList } from '/@/api/mes/common';

  import {
    addMesProOrderworkStep,
    getMesProOrderworkStep,
    updateMesProOrderworkStep,
  } from '/@/api/mes/proorderworkstep';
  import SelectUser from '/@/components/Form/src/components/SelectUser.vue';
  import AutoCodeRule from '/@/components/Form/src/components/AutoCodeRule.vue';
  import { XjrDatePicker } from '/@/components/DatePicker';
  import { MultipleSelect } from '/@/components/MultiplePopup';
  // import Upload from '/@/components/Form/src/components/Upload.vue';
  // import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  // import { Modal } from 'ant-design-vue';
  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);
  const { notification } = useMessage();
  const { t } = useI18n();
  let props = defineProps(['rowData']);
  const rowData = ref({});

  const detailList = ref<any[]>([]);
  // const format = ref('YYYY-MM-DD HH:mm:ss');
  const multipleDialog = ref<boolean>(false);
  function filterColum(column) {
    return column.filter((o) => {
      return o.show == false ? false : true;
    });
  }

  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }
  // const removeList = (index) => {
  //   detailList.value.splice(index, 1);
  // };
  const baseData1 = ref<any>({});

  const emit = defineEmits(['cancel', 'success']);
  // const formRef = ref();
  onMounted(async () => {
    rowData.value = props.rowData;
    console.log('row===', rowData);

    getDetailData();
  });

  watch(
    () => props.rowData?.flag,
    (val) => {
      console.log('监听', val);
      if (val) {
        rowData.value = props.rowData;
        getDetailData();
      }
    },
  );
  function chgSendNum() {
    let sendNum = 0;
    detailList.value.forEach((ele) => {
      if (ele.sendNum) sendNum += parseInt(ele.sendNum);
    });
    baseData1.value.sendNum = sendNum;
    if (baseData1.value.sendNum > baseData1.value.taskNum) {
      notification.error({
        message: 'Tip',
        description: t('派发数量不能超过任务总量'),
      });
      return;
    }
  }
  const getDetailData = async () => {
    baseData1.value = rowData.value;
    if (baseData1.value.id) {
      let data = await getMesProOrderworkStep(baseData1.value?.id);
      baseData1.value = data;
      detailList.value = data.mesProOrderworkStepuserList;
      for (let i = 0; i < detailList.value.length; i++) {
        detailList.value[i].key = i;
      }
    }
  };
  function createRow() {
    detailList.value.push({ key: detailList.value.length, sendNum: '', sendUser: '' });
  }
  function removeRow() {
    // console.log('selectedRowsData.value', selectedRowsData.value, selectedKeys.value);
    detailList.value = detailList.value.filter((e) => {
      let flag = true;
      selectedRowsData.value.forEach((data) => {
        // console.log(data, e, data.index == e.index);
        if ((data.id && data.id == e.id) || data.key == e.key) flag = false;
      });
      // console.log('flag', flag);
      return flag;
    });
  }
  async function handleSubmit() {
    try {
      baseData1.value.mesProOrderworkStepuserList = detailList.value;
      if (
        !baseData1.value.mesProOrderworkStepuserList ||
        baseData1.value.mesProOrderworkStepuserList.length == 0
      ) {
        notification.error({
          message: 'Tip',
          description: t('派工操作不能为空'),
        });
        return;
      }
      let vali = true;
      baseData1.value.mesProOrderworkStepuserList.forEach((ele) => {
        if (!vali) return;
        if (!ele.sendUser || ele.sendUser.length == 0 || !ele.sendNum || ele.sendNum.length == 0) {
          vali = false;
          notification.error({
            message: 'Tip',
            description: t('指派员工、派发数量不能为空'),
          });
          return;
        }
      });
      if (!vali) return;
      console.log('user=values', baseData1.value);

      // TODO custom api
      if (!baseData1.value.id) {
        //false 新增
        await addMesProOrderworkStep(baseData1.value);
        notification.success({
          message: 'Tip',
          description: t('派工成功！'),
        }); //提示消息
      } else {
        await updateMesProOrderworkStep(baseData1.value);
        notification.success({
          message: 'Tip',
          description: t('派工成功！'),
        }); //提示消息
      }
      // formRef.value.resetFields();
      rowData.value = {};
      emit('success');
    } finally {
    }
  }
  function handleClose() {
    emit('cancel');
  }

  const columnsProp = {
    mainKey: 'mesProOrderworkStepuserList',
    columns: [
      // {
      //   title: '#',
      //   dataIndex: 'index',
      // },
      {
        title: '指派员工',
        dataIndex: 'sendUser',
        sorter: true,
      },
      {
        title: '派发数量',
        dataIndex: 'sendNum',
        sorter: true,
      },
    ],
  };
</script>

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

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

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