<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="创建时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="date"
          placeholder="开始日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          @change="() => queryParams.endTime = ''"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="">-</el-form-item>
      <el-form-item label="" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          type="date"
          placeholder="结束日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="分公司" prop="impUnitName">
        <el-select
          v-model="queryParams.impUnitName"
          placeholder="请选择分公司"
          clearable
          filterable
          style="width: 240px"
          @change="handleImpUnitChange"
        >
          <el-option
            v-for="item in impUnitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目部" prop="departName">
        <el-select
          v-model="queryParams.departName"
          placeholder="请选择项目部"
          clearable
          filterable
          style="width: 240px"
          @change="handleDepartChange"
        >
          <el-option
            v-for="item in departOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="分包单位" prop="subUnitName">
        <el-select
          v-model="queryParams.subUnitName"
          placeholder="请选择分包单位"
          clearable
          filterable
          style="width: 240px"
          @change="getTeamList"
        >
          <el-option
            v-for="item in subUnitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="退料工程" prop="proName">
        <el-select
          v-model="queryParams.proName"
          placeholder="请选择退料工程"
          clearable
          filterable
          style="width: 240px"
          @change="getTeamListAndSubUnit"
        >
          <el-option
            v-for="item in proOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="退料班组" prop="teamName">
        <el-select
          v-model="queryParams.teamName"
          placeholder="请选择退料班组"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="item in teamOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="物资名称" prop="typeName">
        <el-select
          v-model="queryParams.typeName"
          placeholder="请选择领料物资名称"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="item in materialNameList"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable filterable style="width: 240px" placeholder="请选择退料状态">
          <el-option
            v-for="dict in dict.type.back_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
          <!-- <el-option
                        v-for="item in taskStatusList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option> -->
        </el-select>
      </el-form-item>

      <el-form-item label="综合搜索" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="输入『 工程名称 / 退料单号 / 班组长 / 联系方式 / 创建人 』关键字搜索"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 460px"
        />
      </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="primary" icon="el-icon-plus" plain size="mini" @click="handleAdd">退料接收</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange" :max-height="650">
      <el-table-column width="60" align="center" label="序号" type="index">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分公司" align="center" prop="impUnitName" width="90" :show-overflow-tooltip="true" />
      <el-table-column label="项目部" align="center" prop="departName" width="90" :show-overflow-tooltip="true" />
      <el-table-column label="分包单位" align="center" prop="subUnitName" width="90" :show-overflow-tooltip="true" />
      <el-table-column label="退料班组" align="center" prop="teamName" width="200" />
      <el-table-column label="工程名称" align="center" prop="proName" width="200" />
      <el-table-column label="退料单号" align="center" prop="code" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="物资名称" align="center" prop="typeName" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="班组长" align="center" prop="backPerson" :show-overflow-tooltip="true" width="100" />
      <el-table-column label="班组长电话" align="center" prop="phone" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="100" />
      <el-table-column label="创建人" align="center" prop="createBy" :show-overflow-tooltip="true" width="100" />
      <el-table-column label="状态" align="center" :show-overflow-tooltip="true" prop="taskStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.back_task_status" :value="scope.row.taskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" plain icon="el-icon-zoom-in" @click="handleSee(scope.row)">查看</el-button>
          <el-button
            size="mini"
            type="primary"
            plain
            icon="el-icon-edit"
            v-if="scope.row.taskStatus != 2 && scope.row.taskStatus != 1"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            v-if="scope.row.taskStatus != 2 && scope.row.taskStatus != 1"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button v-if="scope.row.isZz == 0" size="mini" type="info" icon="el-icon-zoom-in" @click="handlePrint(scope.row)">退料单</el-button>
          <el-button v-if="scope.row.isZz == 1" size="mini" type="primary" icon="el-icon-document" @click="handleDialog(scope.row.directId)">直转单</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 退料单 -->
    <dialogFormByCq
      :dialogTitle="title"
      :isShowFlag.sync="isShowOneFlag"
      :priKey="priKey"
      :rowObj="rowObj"
    ></dialogFormByCq>

    <!-- 提交 -->
    <el-dialog
      v-loading.fullscreen.lock="fullscreenLoading"
      :title="title"
      :visible.sync="openOne"
      append-to-body
      width="400px"
    >
      <div class="submit_box">
        <div>
          <i class="el-icon-circle-check" style="color: #ff9900; font-size: 30px"></i>
        </div>
        <div class="submit_box_title">
          <div>{{ openTextOne }}</div>
          <div>{{ openTextTwo }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openOne = false">返回</el-button>
        <el-button type="primary" @click="submitOpenOneForm()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-loading.fullscreen.lock="fullscreenLoading"
      :title="title"
      :visible.sync="openTwo"
      append-to-body
      width="400px"
    >
      <div class="submit_box_two">
        <div>
          <i class="el-icon-circle-check" style="color: #00c196; font-size: 30px"></i>
        </div>
        <div class="submit_box_title">{{ openTextThree }}</div>
      </div>
      <div slot="footer" class="dialog-footer"></div>
    </el-dialog>

    <!-- 直转单 -->
    <StraightforwardBills ref="straightforwardBills" />
  </div>
</template>

<script>
import {
  getBackApplyList,
  getProjectList,
  backApplyRemove,
  submitBackApply,
  getBmTeamApi,
  getImpUnitListApi, getDepartListByImpUnitApi, getProListByDepartApi, getTeamList, getSubUnitList
} from '@/api/materialsStation'
import dialogFormByCq from './dialogFormByCq.vue'
import {getMaterialTypeList} from "@/api/ma/device";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import StraightforwardBills from '@/views/materialsStation/straight/straightTransferReview/components/StraightforwardBills.vue'

export default {
  name: '',
  dicts: ['back_task_status'],
  components: { dialogFormByCq, Treeselect, StraightforwardBills, StraightforwardBills },
  data() {
    return {
      fullscreenLoading: false,
      type: '',
      isShowOneFlag: false,
      priKey: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', //关键字
        teamId: '', //班组id
        lotId: '', //工程id
        status: '', //状态
        typeId: '', //工机具类型
        time: '',
        agreementCode: '', //协议
        startTime: '',
        endTime: '',
        proId: null,
        impUnitName:'',//分公司
        departName:'',//项目部
        subUnitName:'',//分包单位
        teamName:'',//班组
        proName:'',//工程
        typeName:''//物资名称
      },
      selectTreeProps: {
        children: 'children',
        label: 'name',
        // multiple: false,
        value: 'id'
        // multiple: true,
      },
      unitId: null,
      projectId: null,
      dialogQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dictName: [
          {
            required: true,
            message: '字典名称不能为空',
            trigger: 'blur'
          }
        ],
        dictType: [
          {
            required: true,
            message: '字典类型不能为空',
            trigger: 'blur'
          }
        ]
      },
      openOne: false,
      openTwo: false,
      openTextOne: '',
      openTextTwo: '',
      openTextThree: '',
      companyId: '',
      teamList: [],
      proList: [],
      taskStatusList: [
        {
          name: '待退料',
          id: '37'
        },
        {
          name: '退料已提交',
          id: '38'
        }
      ],
      rowObj: {},
      loadingType: '',
      loadingTotal: 0,
      loadingList: [],
      impUnitOptions: [],   // 分公司下拉
      departOptions: [],    // 项目部下拉
      proOptions: [],       // 工程下拉
      subUnitOptions: [],   // 分包单位下拉
      teamOptions: [],      // 班组下拉
      materialNameList: [],
    }
  },
  created() {
    const end = new Date()
    let start = new Date()
    start.setMonth(start.getMonth() - 1)
    // this.queryParams.time = [this.format(start), this.format(end)]
    this.queryParams.startTime = this.format(start)
    this.queryParams.endTime = this.format(end)
    this.getImpUnitOptions()
    this.handleImpUnitChange()
    this.handleDepartChange()
    this.getTeamList()
    this.getSubUnitList()
    this.getDeviceType()
    this.getList()
    this.initSelectData()
  },

  beforeDestroy() {
    this.$store.commit('clzBack/setClzBackQueryParams', this.queryParams)
  },

  methods: {
    format(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    /** 获取分公司下拉 */
    async getImpUnitOptions() {
      try {
        const res = await getImpUnitListApi() // 调后台接口
        this.impUnitOptions = res.data.map(item => ({
          label: item.impUnitName,   // 这里根据实际字段替换
          value: item.impUnitName
        }))
      } catch (e) {
        console.error('获取分公司下拉失败:', e)
      }
    },
    /** 分公司选择变化，加载项目部 */
    async handleImpUnitChange() {
      this.queryParams.departName = null // 清空项目部已选
      this.departOptions = []            // 清空原有下拉

      try {
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getDepartListByImpUnitApi(params)
        this.departOptions = res.data.map(item => ({
          label: item.departName,   // 项目部名称字段
          value: item.departName
        }))
      } catch (e) {
        console.error('获取项目部下拉失败:', e)
      }
    },
    /** 项目部选择变化，加载工程 */
    async handleDepartChange() {
      this.queryParams.proName = null // 清空工程已选
      this.proOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getProListByDepartApi(params)
        this.proOptions = res.data.map(item => ({
          label: item.proName,   // 工程名称字段
          value: item.proName
        }))
      } catch (e) {
        console.error('获取工程下拉失败:', e)
      }
    },
    /** 项目部选择变化，加载工程 */
    async getTeamListAndSubUnit() {
      this.queryParams.teamName = null // 清空工程已选
      this.teamOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getTeamList(params)
        this.teamOptions = res.data.map(item => ({
          label: item.teamName,   // 工程名称字段
          value: item.teamName
        }))
      } catch (e) {
        console.error('获取班组下拉失败:', e)
      }

      this.queryParams.subUnitName = null // 清空工程已选
      this.subUnitOptions = []            // 清空原有下拉
      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getSubUnitList(params)
        this.subUnitOptions = res.data.map(item => ({
          label: item.subUnitName,
          value: item.subUnitName
        }))
      } catch (e) {
        console.error('获取分包单位下拉失败:', e)
      }
    },
    async getTeamList() {
      this.queryParams.teamName = null // 清空工程已选
      this.teamOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getTeamList(params)
        this.teamOptions = res.data.map(item => ({
          label: item.teamName,   // 工程名称字段
          value: item.teamName
        }))
      } catch (e) {
        console.error('获取班组下拉失败:', e)
      }
    },
    async getSubUnitList() {
      this.queryParams.subUnitName = null // 清空工程已选
      this.subUnitOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getSubUnitList(params)
        this.subUnitOptions = res.data.map(item => ({
          label: item.subUnitName,
          value: item.subUnitName
        }))
      } catch (e) {
        console.error('获取分包单位下拉失败:', e)
      }
    },

    getDeviceType() {
      getMaterialTypeList({ level: 3, skipPermission: 1 }).then(response => {
        let matNameRes = response.data
        this.materialNameList = matNameRes.map((item) => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
    },

    initSelectData() {
      this.GetUnitData()
      this.GetProData()
    },
    // 获取 来往单位 列表数据
    async GetUnitData() {
      const params = {
        // projectId: this.queryParams.proId /*  */,
      }
      const res = await getBmTeamApi({ isAll: 0 })
      this.teamList = res.data
    },
    unitChange(val) {
      setTimeout(() => {
        this.GetProData()
      }, 500)
    },
    // 获取 工程名称 列表数据
    async GetProData() {
      const params = {
        unitId: this.queryParams.unitId
      }
      const res = await getProjectList({ unitId: null })
      this.proList = res.data
      this.queryParams.proId = null
    },
    proChange(val) {
      setTimeout(() => {
        this.GetUnitData()
      }, 500)
    },
    /** 查询列表 startTime,结束日期endTime  */
    async getList() {
      this.loading = true
      // if (this.queryParams.time && this.queryParams.time.length > 0) {
      //   this.queryParams.startTime = this.queryParams.time[0]
      //   this.queryParams.endTime = this.queryParams.time[1]
      // } else {
      //   this.queryParams.startTime = undefined
      //   this.queryParams.endTime = undefined
      // }
      try {
        let params = {
          companyId: this.companyId,
          ...this.queryParams
        }
        const res = await getBackApplyList(params)
        this.typeList = res.data.rows
        this.total = res.data.total
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      const end = new Date()
      let start = new Date()
      start.setMonth(start.getMonth() - 1)
      // this.queryParams.time = [this.format(start), this.format(end)]
      this.projectId = null
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', //关键字
        teamId: '', //班组id
        lotId: '', //工程id
        status: '', //状态
        typeId: '', //工机具类型
        time: '',
        agreementCode: '', //协议
        startTime: this.format(start),
        endTime: this.format(end),
        proId: null,
        impUnitName:'',//分公司
        departName:'',//项目部
        subUnitName:'',//分包单位
        teamName:'',//班组
        proName:'',//工程
        typeName:''//物资名称
      }
      this.$store.commit('clzBack/clzBackQueryParams', this.queryParams)
      this.getImpUnitOptions()
      this.handleImpUnitChange()
      this.handleDepartChange()
      this.getTeamList()
      this.getSubUnitList()
      this.initSelectData()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$emit('returnApply')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$emit('returnEdit', row.id)
    },
    /** 查看按钮操作 */
    handleSee(row) {
      this.$emit('queryReturn', row.id)
    },
    // 退料单
    handleUpdateOrder() {
      this.title = '查看'
      this.isShowOneFlag = true
    },
    // // 提交
    // handleSubmit() {
    //     this.title = '确认操作'
    //     this.openTextOne = '确认提交退料么?'
    //     this.openTextTwo = '确认提交退料么?'
    //     this.openOne = true
    // },
    // submitOpenOneForm() {
    //     this.openTextThree = '提交成功！'
    //     this.openTwo = true
    // },

    handleSubmit(row) {
      this.$modal
        .confirm('是否确认提交所选择的退料任务？')
        .then(() => {
          let param = {
            id: row.id,
            taskId: row.taskId
          }
          submitBackApply(param).then(res => {
            this.getList()
            this.$message.success('操作成功!')
          })
        })
        .catch(() => {})
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // let param = {
      //     id:row.id+ '',
      // }
      this.$modal
        .confirm('是否确认删除所选择的退料任务？')
        .then(() => {
          return backApplyRemove({ id: row.id })
        })
        .then(() => {
          this.getList()
          this.$message.success('操作成功!')
        })
        .catch(() => {})
    },
    handlePrint(row) {
      this.isShowOneFlag = true
      this.rowObj = row
    },
    handleDialog(id) {
      this.$refs.straightforwardBills.openDialog(id)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'material/material_back_apply_info/export',
        {
          ...this.queryParams,
          // startTime: this.queryParams.time[0],
          // endTime: this.queryParams.time[1]
        },
        `退料申请单_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
<style lang="scss" scoped>
.submit_box {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .submit_box_title {
    display: flex;
    flex-direction: column;
    margin-left: 15px;

    :first-child {
      font-size: 14px;
      font-weight: 600;
    }

    :last-child {
      margin-top: 6px;
      font-size: 12px;
    }
  }
}

.submit_box_two {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  margin-left: 30%;

  .submit_box_title {
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    font-size: 18px;
    font-weight: 600;
  }
}

::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
