<template>
  <div class="tenant">
    <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading"
             :selectConfig="selectConfig" :action-list="actionList" @get-list="getList"
             @moreSearch="() => queryDialogVisible = true" :table-events="tableEvents">
    </byTable>

    <!--高级搜索-->
    <el-dialog :title="'高级检索'" v-model="queryDialogVisible" width="500px" destroy-on-close>

      <el-form label-width="auth">
        <!--        <el-form-item label="申请日期">-->
        <!--          <el-date-picker v-model="sourceList.pagination.applyDate" value-format="YYYY-MM-DD" type="daterange"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <el-button @click="handleReset" size="large">重置</el-button>
        <el-button @click="handleQuery" type="primary" size="large">搜索</el-button>
      </template>
    </el-dialog>


    <el-dialog title="处理" v-model="visible" width="500px" destroy-on-close>

      <el-form label-position="right" label-width="auto">
        <el-form-item label="报废数量">
          <el-input-number v-model="formData.scrappedCount" style="width: 100%" :controls="false"
                           disabled></el-input-number>
        </el-form-item>
        <el-form-item label="转良品数量">
          <el-input-number v-model="formData.scrappedToQualifiedCount" style="width: 100%" :controls="false" :min="0"
                           :max="formData.scrappedCount" :precision="0"/>
        </el-form-item>
        <el-form-item label="转次品数量">
          <el-input-number v-model="formData.scrappedToDefectiveCount" style="width: 100%" :controls="false" :min="0"
                           :max="formData.scrappedCount" :precision="0"/>
        </el-form-item>
        <el-form-item label="最终报废数量">
          <el-input-number v-model="formData.resultScrappedCount" style="width: 100%" :controls="false" :min="0"
                           :max="formData.scrappedCount" :precision="0"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="visible = false" size="large">取消</el-button>
        <el-button @click="submit" type="primary" size="large">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="批量处理" v-model="batchVisible" width="1200px" destroy-on-close>

      <el-table :data="handleSelectData">
        <el-table-column prop="code" label="质检单号"/>
        <el-table-column prop="productCustomCode" label="物品编码"/>
        <el-table-column prop="productName" label="物品名称"/>
        <el-table-column prop="scrappedCount" label="报废数量"/>
        <el-table-column prop="scrappedToQualifiedCount" label="报废转良品数量">
          <template #default="scope">
            <el-input-number v-model="scope.row.scrappedToQualifiedCount" style="width: 100%" :controls="false" :min="0"
                             :max="scope.row.scrappedCount" :precision="0"/>
          </template>
        </el-table-column>
        <el-table-column prop="scrappedToDefectiveCount" label="报废转次品数量">
          <template #default="scope">
            <el-input-number v-model="scope.row.scrappedToDefectiveCount" style="width: 100%" :controls="false" :min="0"
                             :max="scope.row.scrappedCount" :precision="0"/>
          </template>
        </el-table-column>
        <el-table-column prop="resultScrappedCount" label="最终报废数量">
          <template #default="scope">
            <el-input-number v-model="scope.row.resultScrappedCount" style="width: 100%" :controls="false" :min="0"
                             :max="scope.row.scrappedCount" :precision="0"/>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="batchVisible = false" size="large">取消</el-button>
        <el-button @click="batchSubmit" type="primary" size="large">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

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

const {proxy} = getCurrentInstance();
const loading = ref(false);

const visible = ref(false);
const batchVisible = ref(false);
const queryDialogVisible = ref(false);

const formData = ref({})

const selectData = ref([]);
const handleSelectData = ref([]);

const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    scrappedHandleStatus: undefined
  },
});

const tableEvents = computed(() => {
  return {
    'selection-change': (val) => {
      selectData.value = val;

      handleSelectData.value = []
      selectData.value.forEach(item => {
        handleSelectData.value.push({...item, resultScrappedCount: item.scrappedCount})
      });
    },
  }
})

const selectConfig = ref([
  {
    label: "状态",
    prop: "scrappedHandleStatus",
    data: [
      {
        label: "待处理",
        value: "1",
      },
      {
        label: "待验证",
        value: "2",
      },
      {
        label: "已验证",
        value: "3",
      },
    ],
  },

  {
    label: "项目组",
    prop: "deptId",
  },

]);


const actionList = computed(() => {
  return [
    {
      text: '批量处理',
      disabled: selectData.value.length === 0,
      action: () => {
        batchVisible.value = true;
      }
    }
  ]
});

const config = computed(() => {
  return [
    {
      type: "selection",
      attrs: {
        checkAtt: "isCheck",
      },
    },
    {
      attrs: {
        label: "质检单号",
        prop: "code",
        align: "left",
      },
    },
    {
      attrs: {
        label: "物品编码",
        prop: "productCustomCode",
        align: "left",
      },
    },
    {
      attrs: {
        label: "物品名称",
        prop: "productName",
        align: "left",
      },
    },
    {
      attrs: {
        label: "规格",
        prop: "productSpec",
        align: "left",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "productUnit",
        align: "left",
      },
    },
    {
      attrs: {
        label: "报废数量",
        prop: "scrappedCount",
        align: "left",
      },
    },
    {
      attrs: {
        label: "报废转良品数量",
        prop: "scrappedToQualifiedCount",
        align: "left",
      },
    },
    {
      attrs: {
        label: "报废转次品数量",
        prop: "scrappedToDefectiveCount",
        align: "left",
      },
    },
    {
      attrs: {
        label: "最终报废数量",
        prop: "resultScrappedCount",
        align: "left",
      },
    },
    {
      attrs: {
        label: "状态",
        prop: "scrappedHandleStatus",
        align: "left",
      },
      render(scrappedHandleStatus) {
        switch (scrappedHandleStatus) {
          case 1:
            return '待处理'
          case 2:
            return '待验证'
          case 3:
            return '已验证'
        }
        return '未知状态';
      },
    },
    {
      attrs: {
        label: "生成时间",
        prop: "createTime",
        align: "left",
        width: 160
      },
    },
    {
      attrs: {
        label: "处理时间",
        prop: "scrappedHandleTime",
        align: "left",
        width: 160
      },
    },
    {
      attrs: {
        label: "操作",
        align: "center",
        fixed: "right",
        width: 120
      },
      renderHTML(row) {
        if (row.scrappedHandleStatus === 1) {
          return [{
            attrs: {
              label: "处理",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              visible.value = true
              formData.value = {...row, resultScrappedCount: row.scrappedCount}
            },
          }]
        }
      }
    }

  ];
});

const getDeptList = () => {
  proxy.get("/jdRefundQualityCheck/deptList", {})
      .then(({data}) => {
        console.log(data)
        selectConfig.value[1].data = data.map((item) => {
          return {
            label: item.deptName,
            value: item.deptId,
          };
        });
      })

  selectConfig.value = JSON.parse(JSON.stringify(selectConfig.value));
}
getDeptList();

const getList = async (req) => {
  loading.value = true;

  sourceList.value.pagination = {...sourceList.value.pagination, ...req}

  const queryData = {...sourceList.value.pagination, ...req, status: [1, 2, 3]};
  const applyDate = queryData.applyDate;
  if (applyDate?.length === 2) {
    delete queryData.applyDate
    queryData.beginTime = applyDate[0]
    queryData.endTime = applyDate[1]
  }

  proxy.get("/jdRefundQualityCheck/getPage", queryData)
      .then(({data}) => {
        sourceList.value.data = data.rows;
        sourceList.value.pagination.total = data.total;

        for (let item of sourceList.value.data) {
          if (item.scrappedHandleStatus === 1) {
            item.isCheck = true
          }
        }
      })
      .finally(_ => {
        loading.value = false;
      })

};

const handleReset = () => {
  sourceList.value.pagination = {
    pageNum: sourceList.value.pagination.pageNum,
    pageSize: sourceList.value.pagination.pageSize,
  };
  handleQuery();
};

const handleQuery = () => {
  queryDialogVisible.value = false;
  getList();
};

const submit = () => {
  const {scrappedCount, scrappedToQualifiedCount, scrappedToDefectiveCount, resultScrappedCount} = formData.value
  if (scrappedCount !== scrappedToQualifiedCount + scrappedToDefectiveCount + resultScrappedCount) {
    ElMessage.error("转良品数量+转次品数量+最终报废数量 必须等于 报废数量")
    return
  }
  proxy.post("/jdRefundQualityCheck/handle", formData.value)
      .then(() => {
        ElMessage.success("处理成功")
        visible.value = false;
        getList()
      })
}

const batchSubmit = () => {
  for (let item of handleSelectData.value) {
    const {scrappedCount, scrappedToQualifiedCount, scrappedToDefectiveCount, resultScrappedCount} = item
    if (scrappedCount !== scrappedToQualifiedCount + scrappedToDefectiveCount + resultScrappedCount) {
      ElMessage.error(`产品【${item.productCustomCode}】转良品数量+转次品数量+最终报废数量 必须等于 报废数量`)
      return
    }
  }
  proxy.post("/jdRefundQualityCheck/batchHandle", handleSelectData.value)
      .then(() => {
        ElMessage.success("批量处理成功")
        batchVisible.value = false;
        getList()
      })
}

getList();

</script>

<style lang='scss' scoped>
.tenant {
  padding: 20px;
}


.el-table .error-row {
  background: rgba(245, 108, 108, 0.68);
}
</style>
