<template>
  <div style="width: 100%; padding: 0px 15px">
    <el-form :model="formData.data" :rules="rules" ref="formDom" label-position="top" :disabled="judgeStatus()">
      <!-- <div class="_t">申购信息</div> -->
      <div style="margin-left:-15px;margin-bottom:15px">
        <TitleInfo :content="'申购信息'"></TitleInfo>
      </div>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="业务公司" prop="corporationId">
            <el-select v-model="formData.data.corporationId" placeholder="请选择" filterable style="width: 100%">
              <el-option v-for="item in companyData" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="申购部门" prop="deptName">
            <el-input v-model="formData.data.deptName" placeholder="请输入" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申购人" prop="subcribeName">
            <el-input v-model="formData.data.subcribeName" placeholder="请输入" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申购时间" prop="subcribeTime">
            <el-date-picker v-model="formData.data.subcribeTime" type="datetime" placeholder="请选择" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="申购说明" prop="subcribeContent">
        <el-input v-model="formData.data.subcribeContent" placeholder="请输入" type="textarea">
        </el-input>
      </el-form-item>
      <!-- <div class="_t">申购明细</div> -->
      <div style="width:100%">
        <div style="width:calc(100% + 80px);margin-left:-45px;background:#F0F2F5;height:15px"></div>
        <div :style="{marginTop:true?'15px':''}" style="margin-left:-15px;margin-bottom:15px">
          <TitleInfo :content="'申购明细'"></TitleInfo>
        </div>
      </div>
      <el-form-item>
        <el-button type="primary" @click="openProduct = true" style="margin: 10px 0">
          添加货品
        </el-button>
        <el-table :data="formData.data.subscribeDetailList">
          <el-table-column prop="goodType" label="货品类型" :formatter="(row) => (row.goodType == 1 ? '产品' : '物料')" />
          <el-table-column prop="code" label="货品编码" />
          <el-table-column prop="name" label="货品名称" min-width="150" />
          <el-table-column prop="spec" label="规格型号" />
          <el-table-column prop="unit" label="单位" :formatter="(row) => dictValueLabel(row.unit, productUnit)" />
          <el-table-column prop="count" label="申购数量" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item :prop="'subscribeDetailList.' + $index + '.count'" :rules="rules.count" :inline-message="true">
                <el-input-number onmousewheel="return false;" v-model="row.count" :precision="4" :controls="false" :min="1" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item :prop="'subscribeDetailList.' + $index + '.remark'" :rules="rules.remark" :inline-message="true">
                <el-input v-model="row.remark" placeholder="请输入" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="zip" label="操作" width="100">
            <template #default="{ $index }">
              <el-button type="primary" link @click="handleRemove($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-dialog v-if="openProduct" v-model="openProduct" title="选择货品" width="90%" append-to-body>
      <!-- <SelectGoods :selectList="acquireSelectList()" @cancel="openProduct = false" @pushGoods="pushGoods"></SelectGoods> -->
      <SelectMaterial @selectMaterial="selectMaterial"></SelectMaterial>
    </el-dialog>
  </div>
</template>

<script setup>
import SelectGoods from "@/components/product/SelectGoods";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
import TitleInfo from "@/components/TitleInfo/index.vue";
import SelectMaterial from "@/components/product/SelectMaterial.vue";
const route = useRoute();
const { proxy } = getCurrentInstance();
// 接收父组件的传值
const props = defineProps({
  queryData: String,
});

let formData = reactive({
  data: {
    subcribeTime: "",
    subscribeDetailList: [],
  },
});
let rules = ref({
  corporationId: [
    { required: true, message: "请选择业务公司", trigger: "change" },
  ],
  deptName: [{ required: true, message: "请输入申购部门", trigger: "blur" }],
  subcribeName: [
    { required: true, message: "请输入申购人名称", trigger: "blur" },
  ],
  subcribeTime: [
    { required: true, message: "请选择申购时间", trigger: "change" },
  ],
  // subcribeContent: [
  //   { required: true, message: "请输入申购事由", trigger: "blur" },
  // ],
  count: [{ required: true, message: "请输入申购数量", trigger: "blur" }],
  // remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
});

let openProduct = ref(false);

const handleRemove = (index) => {
  formData.data.subscribeDetailList.splice(index, 1);
  return ElMessage({
    message: "删除成功！",
    type: "success",
  });
};

const pushGoods = (goods) => {
  if (goods && goods.length > 0) {
    let afterFiltering = [];
    if (
      formData.data.subscribeDetailList &&
      formData.data.subscribeDetailList.length > 0
    ) {
      afterFiltering = goods.filter((item) => {
        let data = formData.data.subscribeDetailList.filter(
          (itemProduct) => itemProduct.bussinessId === item.id
        );
        if (data && data.length > 0) {
          return false;
        }
        return true;
      });
    } else {
      afterFiltering = goods;
    }
    const arr = afterFiltering.map((x) => ({
      goodType: x.goodType,
      code: x.code,
      name: x.name,
      spec: x.spec,
      unit: x.unit,
      productId: x.id,
      count: "",
      remark: "",
    }));
    formData.data.subscribeDetailList =
      formData.data.subscribeDetailList.concat(arr);
    openProduct.value = false;
    return ElMessage({
      message: "添加成功！",
      type: "success",
    });
  } else {
    ElMessage("请选择至少一件物品");
  }
};

const formDom = ref(null);
const handleSubmit = async () => {
  const vaild = await formDom.value.validate();
  if (vaild) {
    if (formData.data.subscribeDetailList.length > 0) {
      return true;
    }
    ElMessage({
      message: "请添加申购明细！",
      type: "info",
    });
    return false;
  }

  return false;
};

const userInfo = useUserStore().user;
onMounted(() => {
  if (!route.query.processType) {
    formData.data.subcribeTime = proxy.parseTime(new Date());
    formData.data.deptName = userInfo.dept.deptName;
    formData.data.subcribeName = userInfo.nickName;
  } else {
  }
  if (route.query.id) {
    proxy
      .post("/flowProcess/getStartData", { flowId: route.query.id })
      .then((res) => {
        formData.data = res;
      });
  }
});

const judgeStatus = () => {
  if (route.query.processType == 20 || route.query.processType == 10) {
    return true;
  }
  if (props.queryData.recordList && props.queryData.recordList.length > 0) {
    let data = props.queryData.recordList.filter(
      (item) => item.status === 2 && item.nodeType !== 1
    );
    if (data && data.length > 0) {
      return true;
    }
  }
  return false;
};

const productUnit = ref([]);
const companyData = ref([]);

const getDict = () => {
  proxy.getDictOne(["unit"]).then((res) => {
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });

  proxy
    .post("/corporation/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      companyData.value = res.rows;
    });
};
getDict();
const getFormData = () => {
  return proxy.deepClone(formData.data);
};
defineExpose({
  getFormData,
  handleSubmit,
});
const acquireSelectList = () => {
  let data = [];
  if (
    formData.data.subscribeDetailList &&
    formData.data.subscribeDetailList.length > 0
  ) {
    data = formData.data.subscribeDetailList.map((item) => {
      return {
        id: item.productId,
        name: item.name,
      };
    });
  }
  return data;
};
const emit = defineEmits(["auxiliaryChange"]);
let auxiliaryData = ref([
  {
    label: "最近合同",
    data: [
      [
        {
          label: "合同编号",
          value: "12312312312456",
          fn: () => {
            console.log(formData.data);
          },
          style: {
            color: "red",
          },
          num: 1,
        },
        {
          label: "合同编号",
          value: "123456",
          fn: () => {
            alert("点击事件");
          },
        },
      ],
    ],
  },
]);
const auxiliaryChange = (data) => {
  emit("auxiliaryChange", data);
};
auxiliaryChange(auxiliaryData);
</script>

<style lang="scss" scoped>
._t {
  margin-bottom: 5px;
  font-size: 14px;
}
</style>
