<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="96px">
      <el-form-item label="物流编号" prop="expressCode">
        <el-input
          v-model="queryParams.expressCode"
          placeholder="请输入物流编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="对方姓名" prop="supplyName">
        <el-input
          v-model="queryParams.supplyName"
          placeholder="请输入对方姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="对方手机" prop="supplyPhone">
        <el-input
          v-model="queryParams.supplyPhone"
          placeholder="请输入对方联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人手机号" prop="ownerPhone">
        <el-input
          v-model="queryParams.ownerPhone"
          placeholder="请输入负责人手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划到货时间" prop="planDate">
        <el-date-picker clearable
                        v-model="queryParams.planDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择计划到货时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="物流公司" prop="expressType">
        <el-select v-model="queryParams.expressType" placeholder="请选择物流公司标识" clearable>
          <el-option
            v-for="dict in dict.type.oa_express_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">

        <el-button
          type="waning"
          plain
          size="mini"
          icon="el-icon-refresh"
          @click="handleRefresh"
        >批量更新状态
        </el-button>

        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <KLPTable v-loading="loading" :data="expressList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="物流编号" align="center" prop="expressCode"/>
      <el-table-column label="数据状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status===0" type="warning">未确认</el-tag>
          <el-tag v-if="scope.row.status===1" type="primary">进行中</el-tag>
          <el-tag v-if="scope.row.status===2" type="success">已完成</el-tag>
          <el-tag v-if="scope.row.status===3" type="danger">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流状态" align="center" prop="status" width="200">
        <template slot-scope="scope">
          <ExpressStatusEditor
            :lastStatus.sync="scope.row.lastStatus"
            :lastUpdateTime.sync="scope.row.lastUpdateTime"
            :expressType="scope.row.expressType"
            @save="val => handleStatusSave(scope.row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="剩余时间" align="center" width="120">
        <template slot-scope="scope">
          <ExpressRemainTime :planDate="scope.row.planDate" :status="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="对方姓名" align="center" prop="supplyName"/>
      <el-table-column label="负责人" align="center" prop="ownerName"/>
      <el-table-column label="负责人手机" align="center" prop="ownerPhone" width="120" />
      <el-table-column label="计划到货时间" align="center" prop="planDate" width="180">
        <template slot-scope="scope">
          <span>{{parseTime(scope.row.planDate,'{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="planDate" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.updateTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="物流公司" align="center" prop="expressType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_express_type" :value="scope.row.expressType"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            v-if="scope.row.status===0"
            @click="handleUpdateStatus(scope.row,1)"
          >确认
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            v-if="scope.row.status===1"
            @click="handleUpdateStatus(scope.row,2)"
          >完成
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            v-if="scope.row.status===1"
            @click="handleRefresh(scope.row)"
          >同步物流状态
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            v-if="scope.row.status!==2 && scope.row.status!==3"
            @click="handleUpdateStatus(scope.row,3)"
          >异常
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.status!==2"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </KLPTable>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物流预览对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="物流编号" prop="expressCode">
          <el-input v-model="form.expressCode" placeholder="请输入物流编号"/>
        </el-form-item>
        <el-form-item label="对方姓名" prop="supplyName">
          <el-input v-model="form.supplyName" placeholder="请输入发货方姓名"/>
        </el-form-item>
        <el-form-item label="对方联系方式" prop="supplyPhone">
          <el-input v-model="form.supplyPhone" placeholder="请输入发货方联系方式"/>
        </el-form-item>

        <el-form-item label="负责人" prop="ownerId">
         <user-select v-model="form.ownerId"></user-select>
        </el-form-item>
        <el-form-item label="负责人手机号" prop="ownerPhone">
          <el-input v-model="form.ownerPhone" placeholder="请输入负责人手机号"/>
        </el-form-item>
        <el-form-item label="计划到货时间" prop="planDate">
          <el-date-picker clearable
                          v-model="form.planDate"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择计划到货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="物流公司标识" prop="expressType">
          <el-select v-model="form.expressType" placeholder="请选择物流公司标识">
            <el-option
              v-for="dict in dict.type.oa_express_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="关联项目" prop="projectId">
          <el-select v-model="form.projectId" filterable placeholder="请选择项目" @change="getReportSummary">
            <el-option
              v-for="item in allProject"
              :key="item.projectId"
              :label="item.projectName"
              :value="item.projectId"
            ></el-option>
          </el-select>
        </el-form-item>-->

        <el-form-item label="发货记录" prop="detailId">
          <el-select v-model="form.detailId" placeholder="请选择发货记录">
            <el-option
              v-for="item in reportDetailList"
              :key="item.detailId"
              :label="item.reportDetail"
              :value="item.detailId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 物流详情弹窗 -->
    <el-dialog
      title="物流详情"
      :visible.sync="detailOpen"
      width="600px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="物流编号">{{ expressDetail.expressCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="数据状态">
          <el-tag v-if="expressDetail.status===0" type="warning">未确认</el-tag>
          <el-tag v-else-if="expressDetail.status===1" type="primary">进行中</el-tag>
          <el-tag v-else-if="expressDetail.status===2" type="success">已完成</el-tag>
          <el-tag v-else-if="expressDetail.status===3" type="error">异常</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="对方姓名">{{ expressDetail.supplyName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="对方手机号">{{ expressDetail.supplyPhone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ expressDetail.ownerName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="负责人手机">{{ expressDetail.ownerPhone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="项目名">{{ expressDetail.projectName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="细节描述">{{ expressDetail.detailName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="当前物流状态">{{ expressDetail.lastStatus || '-' }}</el-descriptions-item>
        <el-descriptions-item label="物流更新时间">{{ expressDetail.lastUpdateTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="计划到货时间">{{ expressDetail.planDate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ expressDetail.updateTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="物流公司">
          <dict-tag :options="dict.type.oa_express_type" :value="expressDetail.expressType"/>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ expressDetail.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 异常登记弹窗表单 -->
    <el-dialog
      title="异常问题登记"
      :visible.sync="questionDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form :model="questionForm" :rules="questionFormRules" ref="questionForm" label-width="100px">
        <el-form-item label="问题描述" prop="description">
          <el-input v-model="questionForm.description" type="textarea" placeholder="请输入问题描述"/>
        </el-form-item>
        <el-form-item label="汇报时间" prop="reportTime">
          <el-date-picker v-model="questionForm.reportTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择汇报时间"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="questionForm.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="questionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitQuestionForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 手动填写物流状态弹窗 -->
    <el-dialog title="手动填写物流状态" :visible.sync="customStatusDialogVisible" width="400px" append-to-body>
      <el-form :model="customStatusForm" label-width="100px">
        <el-form-item label="物流状态">
          <el-input v-model="customStatusForm.lastStatus" placeholder="请输入物流状态" />
        </el-form-item>
        <el-form-item label="更新时间">
          <el-date-picker v-model="customStatusForm.lastUpdateTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择更新时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="customStatusDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCustomStatus">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addExpress, delExpress, getExpress, listExpress, refreshExpress, updateExpress } from "@/api/wms/express";
import { addExpressQuestion } from "@/api/wms/expressQuestion";
// import { listProject } from "@/api/wms/project";
// import { listReportDetailByProjectId } from "@/api/wms/reportDetail";
import UserSelect from "@/components/KLPService/UserSelect/index.vue";
import { EExpressType } from '@/utils/enums';
import ExpressRemainTime from './components/ExpressRemainTime.vue';
import ExpressStatusEditor from './components/ExpressStatusEditor.vue';

export default {
  name: "Express",
  components: {UserSelect, ExpressStatusEditor, ExpressRemainTime},
  dicts: ['oa_express_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      expressDetail:{},
      detailOpen:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物流预览表格数据
      expressList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        expressCode: undefined,
        status: undefined,
        supplyName: undefined,
        supplyPhone: undefined,
        ownerId: undefined,
        ownerPhone: undefined,
        planDate: undefined,
        expressType: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        expressId: [
          {required: true, message: "主键id不能为空", trigger: "blur"}
        ],
        expressCode: [
          {required: true, message: "物流编号不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "数据状态0未确认1进行中2已完成不能为空", trigger: "change"}
        ],
        supplyName: [
          {required: true, message: "供应商姓名不能为空", trigger: "blur"}
        ],
        supplyPhone: [
          {required: true, message: "供应商联系方式不能为空", trigger: "blur"}
        ],
        ownerId: [
          {required: true, message: "负责人id不能为空", trigger: "blur"}
        ],
        ownerPhone: [
          {required: true, message: "负责人手机号不能为空", trigger: "blur"}
        ],
        planDate: [
          {required: true, message: "计划到货时间不能为空", trigger: "blur"}
        ],
        expressType: [
          {required: true, message: "物流公司标识不能为空", trigger: "change"}
        ],
        remark: [
          {required: true, message: "备注不能为空", trigger: "blur"}
        ]
      },
      allProject:[],
      reportDetailList:[],
      // 异常登记弹窗
      questionDialogVisible: false,
      // 异常登记表单
      questionForm: {
        expressId: null,
        description: '',
        reportTime: '',
        status: 0,
        remark: ''
      },
      // 异常登记表单校验
      questionFormRules: {
        description: [{ required: true, message: '问题描述不能为空', trigger: 'blur' }],
        reportTime: [{ required: true, message: '汇报时间不能为空', trigger: 'blur' }]
      },
      currentExceptionRow: null,
      customStatusDialogVisible: false,
      customStatusForm: {
        expressId: null,
        lastStatus: '',
        lastUpdateTime: ''
      }
    };
  },
  created() {
    this.getList();
    // this.getAllProject()
  },
  methods: {
    /** 查询物流预览列表 */
    getList() {
      this.loading = true;
      listExpress(this.queryParams).then(response => {
        this.expressList = response.rows;
        this.total = response.total;
        this.loading = false;
      });


    },
    /*getAllProject() {
      listProject({pageNum: 1, pageSize: 999999999}).then(response => {
        this.allProject = response.rows;
      });
    },*/

    /*getReportSummary() {
      listReportDetailByProjectId(this.form.projectId).then(response => {
        this.reportDetailList = response.data;
      });
    },*/
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },


    // 表单重置
    reset() {
      this.form = {
        expressId: undefined,
        expressCode: undefined,
        status: undefined,
        supplyName: undefined,
        supplyPhone: undefined,
        ownerId: undefined,
        ownerPhone: undefined,
        planDate: undefined,
        expressType: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.expressId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物流预览";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const expressId = row.expressId || this.ids
      getExpress(expressId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改物流预览";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.expressId != null) {
            updateExpress(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addExpress(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },

    handleDetail(row){
      getExpress(row.expressId).then(response => {
        this.loading = false;
        this.expressDetail = response.data;
        this.detailOpen = true;
      });
    },


    // 更新状态
    handleUpdateStatus(row, status) {
      let str = ""
      if (status === 1) {
        str = "是否确认操作，此数据将变化为确认状态"
      } else if (status === 2) {
        str = "确认状态已完成？"
      } else {
        str = "此物流单是否确认发生异常？操作后数据无法恢复"
      }
      if (status === 3) {
        // 弹出异常登记表单
        this.questionForm = {
          expressId: row.expressId,
          description: '',
          reportTime: this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
          status: 0,
          remark: ''
        };
        this.currentExceptionRow = row;
        this.questionDialogVisible = true;
        return;
      }
      this.$modal.confirm(str).then(() => {
        row.status = status
        this.loading = true;
        return updateExpress(row);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    submitQuestionForm() {
      this.$refs.questionForm.validate(valid => {
        if (!valid) return;
        // 新增 expressQuestion
        addExpressQuestion(this.questionForm).then(() => {
          // 新增成功后，更新物流单状态为异常
          const row = this.currentExceptionRow;
          row.status = 3;
          this.loading = true;
          updateExpress(row).then(() => {
            this.loading = false;
            this.getList();
            this.$modal.msgSuccess("异常登记成功，物流单已标记为异常");
          }).finally(() => {
            this.loading = false;
          });
          this.questionDialogVisible = false;
        });
      });
    },

    // 同步物流状态
    handleRefresh(row){
      const expressIds = row.expressId || this.ids;
      if (expressIds.length < 1) {
        this.$modal.msgError("请选择要同步的物流单");
        return;
      }
      refreshExpress(expressIds).then(response => {
        this.getList();
        this.$modal.msgSuccess("同步完成");
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const expressIds = row.expressId || this.ids;
      this.$modal.confirm('是否确认删除物流预览编号为"' + expressIds + '"的数据项？').then(() => {
        this.loading = true;
        return delExpress(expressIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/express/export', {
        ...this.queryParams
      }, `express_${new Date().getTime()}.xlsx`)
    },
    // 计算剩余天数
    getRemainDays(planDate) {
      if (!planDate) return '-';
      const now = new Date();
      const plan = new Date(planDate);
      const diff = plan.getTime() - now.getTime();
      return Math.ceil(diff / (1000 * 60 * 60 * 24));
    },
    // 判断是否超时
    isTimeout(planDate) {
      if (!planDate) return false;
      const now = new Date();
      const plan = new Date(planDate);
      return now.getTime() > plan.getTime();
    },
    isCustomExpress(expressType) {
      const expressTypeList = Object.values(EExpressType);
      return !expressTypeList.includes(expressType);
    },
    openCustomStatusDialog(row) {
      this.customStatusForm = {
        expressId: row.expressId,
        lastStatus: row.lastStatus || '',
        lastUpdateTime: row.lastUpdateTime || ''
      };
      this.customStatusDialogVisible = true;
    },
    submitCustomStatus() {
      if (!this.customStatusForm.lastStatus || !this.customStatusForm.lastUpdateTime) {
        this.$modal.msgError('请填写完整物流状态和更新时间');
        return;
      }
      // 更新expressList中对应项
      const row = this.expressList.find(item => item.expressId === this.customStatusForm.expressId);
      if (row) {
        row.lastStatus = this.customStatusForm.lastStatus;
        row.lastUpdateTime = this.customStatusForm.lastUpdateTime;
        // 可选：直接调用后端接口保存
        updateExpress(row).then(() => {
          this.$modal.msgSuccess('保存成功');
          this.getList();
        });
      }
      this.customStatusDialogVisible = false;
    },
    handleStatusSave(row, val) {
      row.lastStatus = val.lastStatus;
      row.lastUpdateTime = val.lastUpdateTime;
      updateExpress(row).then(() => {
        this.$modal.msgSuccess('保存成功');
        this.getList();
      });
    }
  }
};
</script>
