<template>
  <div class="mesHolidayType-container">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
      <el-form :model="queryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="queryParams.searchKey" clearable="" placeholder="请输入模糊查询关键字"/>

            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb5">
            <el-form-item label="日期范围:" prop="dateRange">
							<el-date-picker type="daterange" v-model="queryParams.dateRange"  value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />

              <!-- <el-date-picker
                  style="width:120px"
                  v-model="queryParams.startDate"
                  type="date"
                  placeholder="选择开始日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
              />
              -
              <el-date-picker
                  style="width:120px"
                  v-model="queryParams.endDate"
                  type="date"
                  placeholder="选择结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10">
            <el-form-item label="订单号">
              <el-input v-model="queryParams.produceOrderNo" clearable="" placeholder="请输入订单号"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10">
            <el-form-item label="物料编码">
              <el-input v-model="queryParams.materialCode" clearable="" placeholder="请输入物料编码"/>

            </el-form-item>
          </el-col>
          <!--          <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">-->
          <!--            <el-form-item label="公休日类型">-->
          <!--              <el-select clearable="" v-model="queryParams.holidayType" placeholder="请选择公休日类型">-->
          <!--                <el-option v-for="(item,index) in dl('HolidayType')" :key="index" :value="item.code" :label="`[${item.code}] ${item.value}`" />-->

          <!--              </el-select>-->

          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10">
            <el-form-item>
              <el-button-group style="display: flex; align-items: center;">
                <el-button type="primary"  icon="ele-Search" @click="handleQuery" > 查询 </el-button>
                <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>
                <!-- <el-button icon="ele-ZoomIn" @click="changeAdvanceQueryUI" v-if="!showAdvanceQueryUI" style="margin-left:5px;"> 高级查询 </el-button>
                <el-button icon="ele-ZoomOut" @click="changeAdvanceQueryUI" v-if="showAdvanceQueryUI" style="margin-left:5px;"> 隐藏 </el-button> -->

                <el-button type="primary" style="margin-left:5px;" icon="ele-Operation" @click="PlanSend" :disabled="selectionList.length != 1" > 计划排配 </el-button>
                <!--                <el-button type="primary" style="margin-left:5px;" icon="ele-Promotion" @click="PlanPost" :disabled="selectionList.length != 1"  > 计划下发 </el-button>-->

              </el-button-group>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table
          ref="tableRef"
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          tooltip-effect="light"
          row-key="id"
          @sort-change="sortChange"
          @selection-change="onSelectionChange"
          border="">
        <el-table-column prop="date" label="发货周期表" width="250"  align="center" fixed="left" >
          <el-table-column type="selection"   width="55" align="center" />
          <el-table-column type="index" label="序号" width="55" align="center" fixed="left"/>
          <el-table-column prop="planStatus" label="计划状态"  show-overflow-tooltip="" fixed="left">
            <template #default="scope">
              {{['未排产','排产中','已完成'][scope.row.planStatus]}}
            </template>
          </el-table-column>
          <el-table-column prop="customerCode" label="客户"  show-overflow-tooltip="" fixed="left"/>
          <el-table-column prop="produceOrderNo" label="订单号"  show-overflow-tooltip="" fixed="left" width="120" />
          <el-table-column prop="materialCode" label="物料编码"  show-overflow-tooltip="" fixed="left" width="120" />
          <el-table-column prop="num" label="生产数量"  show-overflow-tooltip="" fixed="left" />
          <!-- <el-table-column prop="pcs" label="出数"  show-overflow-tooltip="" fixed="left" /> -->
          <!-- <el-table-column prop="pcsLength" label="出数长度(m)"  show-overflow-tooltip="" fixed="left" /> -->
        </el-table-column>
        <el-table-column  label="数量" width="150"  align="center" fixed="left" >
          <template #default="scope">
            <div class="planSendNum">计划发货数量</div>
            <div class="alreadyNum">已排产数量</div>
            <div class="diffNum">差异数量</div>
          </template>
        </el-table-column>
        <!--   动态日期列     -->
        <el-table-column prop="date" label="日期"   align="center" >
          <el-table-column v-for="date in dateList" :prop="date" :label="date"  align="center"  show-overflow-tooltip="" width="100" >
            <template #header>
              <div class="date">{{date}}</div>
              <div class="week">{{
                  ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][new Date(date).getDay()]
                }}</div>
            </template>
            <template #default="scoped">
              <div>
                <!--                  :style="{backgroundColor:scoped.row.dateList[date]?'#fff':'green'}"-->

                <div class="planSendNum" :class="{hasNum:!!scoped.row.dateList[date]?.planSendNum}">{{scoped.row.dateList[date]?.planSendNum || 0 }}</div>
                <div class="alreadyNum"  :class="{hasNum:!!scoped.row.dateList[date]?.alreadyNum}">{{scoped.row.dateList[date]?.alreadyNum || 0 }}</div>
                <div class="diffNum"  :class="{hasNum:!!scoped.row.dateList[date]?.diffNum}">{{scoped.row.dateList[date]?.diffNum || 0 }}</div>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
        <!--        <el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip="" v-if="auth('mesHolidayType/update') || auth('mesHolidayType/delete')">-->
        <!--          <template #default="scope">-->
        <!--            <el-button icon="ele-Edit" size="small" text="" type="primary" @click="openEditMesHolidayType(scope.row)" v-auth="'mesHolidayType/update'"> 编辑 </el-button>-->
        <!--            <el-button icon="ele-Delete" size="small" text="" type="primary" @click="delMesHolidayType(scope.row)" v-auth="'mesHolidayType/delete'"> 删除 </el-button>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <el-pagination
          v-model:currentPage="tableParams.page"
          v-model:page-size="tableParams.pageSize"
          :total="tableParams.total"
          :page-sizes="[10, 20, 50, 100, 200, 500]"
          small=""
          background=""
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
      />
      <printDialog
          ref="printDialogRef"
          :title="printMesHolidayTypeTitle"
          @reloadTable="handleQuery" />
    </el-card>
    <el-dialog v-model="openPlanDialog" width="80%" draggable=""   destroy-on-close :fullscreen="fullScreen">
      <template #header>
        <div style="color: #fff;display: flex;align-items: center;justify-content: space-between;">
          <span>计划排配</span>
          <el-icon size="16" @click="fullScreen = !fullScreen" style="margin-right: 16px; display: block; vertical-align: middle;cursor: pointer">
            <ele-FullScreen v-if="!fullScreen" />
            <ele-Notification v-else />
          </el-icon>
        </div>
      </template>
      <el-form :model="queryParams" ref="searchFormRef" inline :rules="searchRule">
        <el-form-item label="工厂选择:" prop="factoryCode">
          <el-select clearable="" filterable="" v-model="queryParams.factoryCode" placeholder="请选择所属工厂编码">
            <el-option v-for="(item, index) in  mesFactoryFactoryCodeDropdownList" :key="index"
                       :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期:" prop="startDate">
          <el-date-picker
              v-model="queryParams.startDate"
              type="date"
              placeholder="选择开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期:" prop="endDate">
          <el-date-picker
              v-model="queryParams.endDate"
              type="date"
              placeholder="选择结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="ele-Search" @click="getPlanDetail"  > 查询 </el-button>
          <span  style="margin-left: 20px;">
            计划生产数量： <el-tag effect="light" type="warning"> {{ orderProductData.num }}
    </el-tag>，已排期数量:<el-tag effect="light" type="success">{{ orderProductData.planNum }}</el-tag>
          </span>
        </el-form-item>
      </el-form>
      <el-table
          :data="detailTable"
          style="width: 100%;margin-top:12px;"
          v-loading="loading"
          tooltip-effect="light"
          row-key="id"
          border="">
        <el-table-column  label="" width="150"  align="center" fixed="left" >
          <template #default="scope">
            <div class="item">产能占用</div>
            <div class="item">已排产</div>
            <div class="item">排产数量</div>
            <!-- <div class="item">排产数量(张数)</div>
            <div class="item">电晕长度(米)</div> -->
          </template>
        </el-table-column>
        <el-table-column v-for="date in dateList" :prop="date" :label="date"  align="center"  show-overflow-tooltip="" width="100" >
          <template #header>
            <div class="date">{{date}}</div>
            <div class="week">{{
                ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][new Date(date).getDay()]
              }}</div>
          </template>
          <template #default="scoped">
            <div class="item">{{scoped.row[date].num || 0}}/{{ scoped.row[date].maxCapacity || 0 }}</div>
            <div class="item">{{scoped.row[date].productPlanNum || 0}}</div>
            <div class="item">
              <el-input-number type="number" min="0" v-model="scoped.row[date].inputNum" ></el-input-number>
            </div>
            <!-- <div class="item">
              <el-input v-model="scoped.row[date].numZ" :disabled="true"></el-input>
            </div>
            <div class="item">
              <el-input v-model="scoped.row[date].numM" :disabled="true"></el-input>
            </div> -->
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">关 闭</el-button>
					<el-button type="primary" @click="savePlan">确 定</el-button>
				</span>
      </template>
    </el-dialog>

    <!--  计划下发  -->
    <el-dialog v-model="openPlanPostDialog" width="40%" draggable=""   destroy-on-close :fullscreen="fullScreen">
      <template #header>
        <div style="color: #fff;display: flex;align-items: center;justify-content: space-between;">
          <span>计划下发</span>
          <el-icon size="16" @click="fullScreen = !fullScreen" style="margin-right: 16px; display: block; vertical-align: middle;cursor: pointer">
            <ele-FullScreen v-if="!fullScreen" />
            <ele-Notification v-else />
          </el-icon>
        </div>
      </template>
      <el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="日排产数据" prop="planCode">
              <el-select clearable filterable  v-model="ruleForm.planCode" placeholder="请选择日排产数据" >
                <el-option v-for="(item, index) in planList" :key="index" :value="item.value" :label="`${item.value}`"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="ruleForm.reMark" placeholder="请输入备注" maxlength="100" show-word-limit clearable >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="postPlan">下发</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup="" name="mesHolidayType">
import {onMounted, ref, watchEffect} from "vue";
import {ElMessageBox, ElMessage, type FormRules} from "element-plus";
import { auth } from '/@/utils/authFunction';
import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import { formatDate } from '/@/utils/formatTime';


import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import {GenProducePlan, ProducePlanView, QueryPlanPage} from "/@/api/mes/mesProduceOrder";
import {getMesFactoryFactoryCodeDropdown} from "/@/api/mes/mesRuleProcessProdCycle";


const showAdvanceQueryUI = ref(false);
const printDialogRef = ref();
const editDialogRef = ref();
const loading = ref(false);
const tableData = ref<any>([]);
const queryParams = ref<any>({
  startDate: formatDate(new Date(),'YYYY-mm-dd'),
  endDate:formatDate(new Date(new Date().valueOf() + 7 * 86400000),'YYYY-mm-dd')
});
const tableParams = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});
// onMounted(() => {
//   queryParams.value.startDate = formatDate(new Date(),'YYYY-mm-dd');
//   queryParams.value.endDate = formatDate(new Date(new Date().valueOf() + 14 * 86400000),'YYYY-mm-dd');
// })

queryParams.value.dateRange = [queryParams.value.startDate,queryParams.value.endDate];

const mesFactoryFactoryCodeDropdownList = ref<any>([]);
const getMesFactoryFactoryCodeDropdownList = async () => {
  let list = await getMesFactoryFactoryCodeDropdown();
  mesFactoryFactoryCodeDropdownList.value = list.data.result ?? [];
};
getMesFactoryFactoryCodeDropdownList();

const printMesHolidayTypeTitle = ref("");
const editMesHolidayTypeTitle = ref("");

// 改变高级查询的控件显示状态
const changeAdvanceQueryUI = () => {
  showAdvanceQueryUI.value = !showAdvanceQueryUI.value;
}

// 选择行变更
const selectionList = ref([]);
const tableRef = ref();
const onSelectionChange = () => {
  selectionList.value = tableRef.value.getSelectionRows();
}

let fullScreen = ref(false);


const  getDateRange = (startDate, endDate) => {
  // 确保传入的日期字符串是有效的
  const start = new Date(startDate);
  const end = new Date(endDate);

  // 验证开始日期是否小于结束日期
  if (start > end) {
    // throw new Error('开始日期不能晚于结束日期');
    queryParams.value.startDate = null;
    return ElMessage.warning("开始日期不能晚于结束日期");
  }

  // 初始化一个空数组来存储日期
  const dateArray = [];

  // 循环从开始日期到结束日期
  let currentDate = new Date(start);
  while (currentDate <= end) {
    // 将当前日期格式化为YYYY-MM-DD格式并添加到数组中
    const formattedDate = currentDate.getFullYear() + '-' +
        ('0' + (currentDate.getMonth() + 1)).slice(-2) + '-' +
        ('0' + currentDate.getDate()).slice(-2);
    dateArray.push(formattedDate);

    // 将当前日期增加一天
    currentDate.setDate(currentDate.getDate() + 1);
  }

  // return dateArray;
  dateList.value = dateArray
}
const detailTable = ref([]);

// 计划排配
const openPlanDialog = ref(false);
const dateList = ref([]);
const PlanSend = ()=>{
  detailTable.value = [];
  queryParams.value.factoryCode = null;
  openPlanDialog.value = true;
  // request
  // getPlanDetail();
}

const searchFormRef = ref();
const datePlanData = ref({});
const orderProductData = ref({});
const getPlanDetail = ()=>{
  searchFormRef.value.validate(async (isValid: boolean, fields?: any) => {
    if (isValid) {
      let values = ruleForm.value;
      // request
      let res = await ProducePlanView({
        factoryCode:queryParams.value.factoryCode,
        produceOrderProductId:selectionList.value?.[0]?.id,
        startDate:queryParams.value.dateRange[0],
        endDate:queryParams.value.dateRange[1],
      })
      let datas = res?.data?.result || {};
      orderProductData.value = datas.oderProductData;
      // 赋初始绑定字段
      dateList.value.forEach(date=>{
        if(!datas.item[date]){
          datas.item[date] = {
            maxCapacity:0,
            num:0,
            numZ:0,
            numM:0,
            productPlanNum:0,
          }
        }
      })
      detailTable.value = [datas.item]
      console.log(detailTable.value);
      // datePlanData.value = res.data.result ?? {};
    }else{
      ElMessage({
        message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
        type: 'error',
      });
    }
  })
}

const cancel = ()=>{
  openPlanDialog.value = false;
  openPlanPostDialog.value = false;
  ruleForm.value = {
    planCode:"",
    reMark:""
  }
  // handleQuery();
}

const savePlan = ()=>{
  searchFormRef.value.validate(async (isValid: boolean, fields?: any) => {
    if (isValid) {
      let planNumDateList = [];
      let datas = detailTable.value[0] || {};
      for (let key in datas) {
        if(key.includes('-') && datas[key].inputNum && datas[key].inputNum>0){
          planNumDateList.push({
            date:key,
            num:datas[key].inputNum
          })
        }
      }
      if(planNumDateList.length==0){
        ElMessage.error('请输入生产计划数量');
        return;
      }
      GenProducePlan({
        factoryCode:queryParams.value.factoryCode,
        produceOrderProductId:selectionList.value?.[0]?.id,
        items:planNumDateList
      }).then(res=>{
        ElMessage({
          message: `操作成功`,
          type: 'success',
        });
        cancel();
        handleQuery();
      }).catch(()=>{})
    }else{
      ElMessage({
        message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
        type: 'error',
      });
    }
  })
}

// 计划下发
const openPlanPostDialog = ref(false);
const ruleForm = ref({
  planCode:"",
  reMark:""
})
const rules = ref<FormRules>({
  planCode: [{required: true, message: '请选择计划！', trigger: 'blur',},],
});
const searchRule = ref<FormRules>({
  factoryCode: [{required: true, message: '请选择工厂！', trigger: 'blur',},],
  startDate: [{required: true, message: '请选择开始日期！', trigger: 'blur',},],
  endDate: [{required: true, message: '请选择结束日期！', trigger: 'blur',},],
});
const PlanPost = ()=>{
  openPlanPostDialog.value = true;
  getPlanList();
}
const planList = ref([]);
const getPlanList = ()=>{
  // request
}
const ruleFormRef = ref();
const postPlan = ()=>{
  ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
    if (isValid) {
      let values = ruleForm.value;
      // request

    }else{
      ElMessage({
        message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
        type: 'error',
      });
    }
  })
}

// 查询操作
const handleQuery = async () => {
  loading.value = true;
  queryParams.value.startDate = queryParams.value.dateRange[0];
  queryParams.value.endDate = queryParams.value.dateRange[1];
  var res = await QueryPlanPage(Object.assign(queryParams.value, tableParams.value));
  tableData.value = res.data.result?.items ?? [];
  tableParams.value.total = res.data.result?.total;
  loading.value = false;
};
watchEffect(() => {
  console.log('查询日期变化了');
  // 自动更新 日期列
  if(queryParams.value.dateRange.length==2){
    getDateRange(queryParams.value.dateRange[0], queryParams.value.dateRange[1]);
    if(openPlanDialog.value == true){
      if(queryParams.value.factoryCode){
        getPlanDetail()
      }
    }else{
      handleQuery();
    }
  }
});


// 列排序
const sortChange = async (column: any) => {
  queryParams.value.field = column.prop;
  queryParams.value.order = column.order;
  await handleQuery();
};

// 打开新增页面
const openAddMesHolidayType = () => {
  editMesHolidayTypeTitle.value = '添加公休日类型';
  editDialogRef.value.openDialog({
    holidayTypeStatus:1
  });
};


// 改变页面容量
const handleSizeChange = (val: number) => {
  tableParams.value.pageSize = val;
  handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
  tableParams.value.page = val;
  handleQuery();
};

handleQuery();
</script>
<style scoped>
:deep(.el-ipnut),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}
.hasNum{
  background-color: yellow !important;
}
.diffNum{
  width:100%;
  text-align: center;
  height:30px;
  line-height:30px;
}
.alreadyNum{
  width:100%;
  text-align: center;
  height:30px;
  line-height:30px;
  border-top:1px solid #eee;
  border-bottom:1px solid #eee;
}
.planSendNum{
  width:100%;
  text-align: center;
  height:30px;
  line-height:30px;
}
.item{
  width:100%;
  text-align: center;
  height:30px;
  line-height:30px;
}
.item+.item{
  border-top:1px solid #eee;
}
</style>

