<template>
  <div class="tenant">
    <byTable
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      highlight-current-row
      :table-events="{
        select: selectRow,
        'select-all': selectRow,
      }"
      :action-list="[
        {
          text: '转生产',
          disabled: selectData.length === 0,
          action: () => transferToProduction(),
        },
        {
          text: '采购',
          disabled: selectData.length === 0,
          action: () => start(),
        },
      ]"
      @get-list="getList">
      <template #claimTime="{ item }">
        <div>
          <span v-if="item.claimTime">{{ item.claimTime }}</span>
          <span v-else>未到账</span>
        </div>
      </template>
    </byTable>

    <el-dialog title="转生产" v-if="dialogVisible" v-model="dialogVisible" width="1200" v-loading="loadingDialog">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #details>
          <div style="width: 100%">
            <el-table :data="formData.data.list" style="width: 100%; margin-top: 16px">
              <el-table-column prop="productCode" label="物品编码" width="140" />
              <el-table-column prop="productName" label="物品名称" min-width="220" />
              <el-table-column prop="productUnit" label="单位" width="100" />
              <el-table-column prop="expendQuantity" label="待处理数量" width="120" />
              <el-table-column label="转生产数量" width="160">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item :prop="'list.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true">
                      <el-input-number v-model="row.quantity" placeholder="请输入数量" style="width: 100%" :precision="0" :controls="false" :min="0" />
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="完工期限" width="160">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item :prop="'list.' + $index + '.time'" :rules="rules.time" :inline-message="true">
                      <el-date-picker v-model="row.time" type="date" placeholder="请选择完工期限" value-format="YYYY-MM-DD" :disabled="true" />
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="80" fixed="right">
                <template #default="{ row, $index }">
                  <el-button type="primary" link @click="handleDelete($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const loading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    status: "15",
  },
});
const config = computed(() => {
  return [
    {
      type: "selection",
    },
    {
      attrs: {
        label: "外销合同编号",
        prop: "contractCode",
      },
    },
    {
      attrs: {
        label: "合同到账时间",
        slot: "claimTime",
      },
    },
    {
      attrs: {
        label: "业务员",
        prop: "userName",
      },
    },
    {
      attrs: {
        label: "版本号",
        prop: "contractVersion",
      },
    },
    {
      attrs: {
        label: "产品编码",
        prop: "productCode",
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "productUnit",
      },
    },
    {
      attrs: {
        label: "待处理数量",
        prop: "expendQuantity",
      },
    },
    {
      attrs: {
        label: "详情",
        prop: "remark",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "140",
        align: "center",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "采购",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              selectData.value = [row];
              start();
            },
          },
          {
            attrs: {
              label: "转生产",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              transferToProduction(row);
            },
          },
        ];
      },
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/contractProduct/page", sourceList.value.pagination).then((message) => {
    console.log(message);
    sourceList.value.data = message.rows;
    sourceList.value.pagination.total = message.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const selectData = ref([]);
const selectRow = (data) => {
  selectData.value = data;
};
const start = () => {
  if (selectData.value.length > 0) {
    let ids = selectData.value.map((x) => x.id).join();
    proxy.$router.replace({
      path: "/platform_manage/process/processApproval",
      query: {
        flowKey: "purchase_flow",
        type: "handoverSlip",
        ids,
      },
    });
  } else {
    return ElMessage({
      message: "请勾选数据！",
      type: "info",
    });
  }
};
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {
    list: [],
  },
});
const formConfig = computed(() => {
  return [
    // {
    //   label: "基本信息",
    // },
    // {
    //   type: "select",
    //   prop: "warehouseId",
    //   label: "工单类型",
    //   data: [],
    // },
    // {
    //   type: "input",
    //   prop: "remark",
    //   label: "备注",
    //   itemType: "textarea",
    // },
    {
      type: "slot",
      slotName: "details",
      label: "产品明细",
    },
  ];
});
const rules = ref({
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
});
const transferToProduction = (row) => {
  if (row && row.id) {
    formData.data = {
      list: [
        {
          sourceId: "1",
          source: "1",
          productId: row.productId,
          productCode: row.productCode,
          productName: row.productName,
          productUnit: row.productUnit,
          expendQuantity: row.expendQuantity,
          quantity: undefined,
        },
      ],
    };
  } else {
    formData.data = {
      list: selectData.value.map((item) => {
        return {
          sourceId: "1",
          source: "1",
          productId: item.productId,
          productCode: item.productCode,
          productName: item.productName,
          productUnit: item.productUnit,
          expendQuantity: item.expendQuantity,
          quantity: undefined,
        };
      }),
    };
  }
  dialogVisible.value = true;
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (!(formData.data.list && formData.data.list.length > 0)) {
      return ElMessage("请至少添加一条产品明细");
    }
    loadingDialog.value = true;
    proxy.post("/workOrder/addBatch", formData.data.list).then(
      () => {
        ElMessage({
          message: "提交成功",
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        loadingDialog.value = false;
      }
    );
  });
};
const handleDelete = (index) => {
  formData.data.list.splice(index, 1);
};
</script>

<style lang="scss" scoped>
.tenant {
  margin: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
