<template>
  <ele-modal
    width="80%"
    :visible="visible"
    append-to-body
    custom-class="ele-dialog-form"
    :title="title"
    :close-on-click-modal="false"
    :before-close="handleBeforeClose"
    maxable
  >
    <header-title title="基本信息"></header-title>
    <el-form
      :model="addForm"
      :rules="formRules"
      ref="ruleFormRef"
      label-width="120px"
      v-loading="loading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="类型" required prop="itemType">
            <DictSelection
              dictName="记录规则事项类型"
              clearable
              v-model="addForm.itemType"
              disabled
            >
            </DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="执行方式" required prop="executeMethod">
            <DictSelection
              dictName="记录规则执行方式"
              clearable
              v-model="addForm.executeMethod"
              disabled
            >
            </DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="关联任务">
            <el-input
              v-model="addForm.itemTaskName"
              placeholder="请输入任务名称"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="检查开始时间" required prop="checkStartTime">
            <el-date-picker
              v-model="addForm.checkStartTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              style="width: 100%"
              :picker-options="{
                disabledDate: (time) => time.getTime() > Date.now()
              }"
              @change="computedDuration"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检查结束时间" required prop="checkFinishTime">
            <el-date-picker
              v-model="addForm.checkFinishTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              style="width: 100%"
              :picker-options="{
                disabledDate: (time) => time.getTime() > Date.now()
              }"
              @change="computedDuration"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执行人">
            <el-select
              v-model="addForm.teamId"
              placeholder="请选择班组"
              filterable
              style="width: 120px"
              @change="checkTeamList(addForm.teamId)"
            >
              <el-option
                v-for="item in teamList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="addForm.executeUsersIds"
              placeholder="请选择执行人"
              filterable
              multiple
              @change="changeId"
            >
              <div class="checkboxWrapper">
                <el-checkbox v-model="checked" @change="checkChange">
                  全选
                </el-checkbox>
              </div>
              <el-option
                v-for="item in teamUserList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工时">
            <el-input
              placeholder="请输入"
              v-model="addForm.duration"
              type="number"
              min="0"
              step="0.1"
              @change="durationChagne"
            >
              <template slot="append">
                <div style="width: 40px; box-sizing: border-box">小时</div>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="modal-footer">
        <el-button
          v-if="type != 'detail'"
          :loading="butLoading"
          type="primary"
          @click="submit('submit')"
          :disabled="productionInfo && productionInfo.executeStatus == 2"
        >
          一键报工
        </el-button>

        <el-button v-if="productionInfo" @click="handleBeforeClose">
          关闭
        </el-button>
      </div>
    </template>
  </ele-modal>
</template>

<script>
  import DictSelection from '@/components/Dict/DictSelection.vue';
  import SelectUser from '@/components/select/SelectUser/index.vue';
  import { saveRuleRecord } from '@/api/producetaskrulerecord/index.js';
  import { getTeam } from '@/api/produce/job.js';
  import { getById } from '@/api/producetaskrecordrulesrecord/index';

  export default {
    components: { SelectUser },
    emits: ['reload'],
    props: {
      isTempRecord: {
        type: Number,
        default: 0
      }
    },
    data() {
      const formDate = {
        id: null,
        workshopArea: '',
        checkFinishTime: '',
        checkValidity: null,
        checkValidityUnit: '',
        conclusion: null,
        isTempRecord: this.isTempRecord,
        details: [],
        planList: [],
        deviceId: 0,
        deviceName: '',
        batchNo: '',
        brandNo: '',
        executeMethod: 0,
        formingNum: 0,
        itemType: 0,
        produceRoutingId: 0,
        produceRoutingName: '',
        produceTaskConfigId: 0,
        produceTaskId: 0,
        produceTaskName: '',
        productCode: '',
        productModel: '',
        productName: '',
        recordRulesClassify: null,
        ruleId: 0,
        ruleName: '',
        reportWorkType: 0,
        specification: '',
        workOrderCode: '',
        workOrderId: 0,
        itemTaskName: '',
        teamId: null,
        checkStartTime: '',
        checkFinishTime: '',
        duration: null,
        executeUsers: [],
        executeUsersIds: []
      };

      return {
        visible: false,
        formDate,
        addForm: JSON.parse(JSON.stringify(formDate)),
        formRules: {
          checkFinishTime: [
            { required: true, message: '请选择检查完成时间', trigger: 'blur' },
            { required: true, message: '请选择检查完成时间', trigger: 'change' }
          ],
          conclusion: [
            { required: true, message: '请选择结论', trigger: 'blur' },
            { required: true, message: '请选择结论', trigger: 'change' }
          ],
          checkValidity: [
            { required: true, message: '请输入检查有效期', trigger: 'blur' },
            { required: true, message: '请输入检查有效期', trigger: 'change' }
          ],
          checkValidityUnit: [
            {
              required: true,
              message: '请选择检查有效期单位',
              trigger: 'blur'
            },
            {
              required: true,
              message: '请选择检查有效期单位',
              trigger: 'change'
            }
          ],
          checkStartTime: [
            { required: true, message: '请选择检查开始时间', trigger: 'blur' },
            {
              required: true,
              message: '请选择检查开始时间',
              trigger: 'change'
            },
            {
              validator: (rule, value, callback) => {
                if (!value) return callback();
                const start = new Date(value).getTime();
                const now = Date.now();
                if (start > now) {
                  callback(new Error('开始时间不能超过当前时间'));
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }
          ],
          checkFinishTime: [
            { required: true, message: '请选择检查完成时间', trigger: 'blur' },
            {
              required: true,
              message: '请选择检查完成时间',
              trigger: 'change'
            },
            {
              validator: (rule, value, callback) => {
                if (!value) return callback();
                const start = new Date(this.addForm.checkStartTime).getTime();
                const finish = new Date(value).getTime();
                const now = Date.now();
                if (finish <= start) {
                  callback(new Error('结束时间必须大于开始时间'));
                } else if (finish > now) {
                  callback(new Error('结束时间不能超过当前时间'));
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }
          ]
        },
        productionInfo: null,
        list: [],
        ruleInfo: null,
        showSelectUser: false,
        currentRow: null,
        butLoading: false,
        // 工艺路线
        workOrderInfo: null,
        // 加载中 loading
        loading: false,
        title: '任务确认',
        // 编辑 或者是  详情 edit detila
        type: 'edit',
        checked: false,
        teamUserList: [],
        teamList: [],
        teamAllList: [],
        checked: false
      };
    },
    computed: {},
    mounted() {
      if (localStorage.getItem('singleUserInfo') == '1') {
        const data = JSON.parse(localStorage.getItem('chooseUserInfo'));
        this.getTeamList(data.teamId);
      } else {
        this.getTeamList(this.$store.state.user.info.teamId);
      }
    },
    methods: {
      openView(productionInfo, workOrderInfo) {
        this.type = 'detail';
        this.open(productionInfo, workOrderInfo);
      },
      open(productionInfo, workOrderInfo) {
        console.log(
          'productionInfo, workOrderInfo',
          productionInfo,
          workOrderInfo
        );
        this.visible = true;
        this.productionInfo = productionInfo;
        this.workOrderInfo = workOrderInfo;

        // 存在缓存记录
        if (this.productionInfo.recordId != null) {
          // 查询详情
          this.getCacheInfo();
        } else {
          this.addForm.batchNo = workOrderInfo.batchNo;
          this.addForm.executeMethod = productionInfo.executeMethod;
          this.addForm.formingNum = workOrderInfo.formingNum;
          this.addForm.itemType = productionInfo.itemType;
          this.addForm.produceRoutingId = workOrderInfo.produceRoutingId;
          this.addForm.produceRoutingName = workOrderInfo.produceRoutingName;
          this.addForm.produceTaskConfigId = productionInfo.produceTaskConfigId;
          this.addForm.produceTaskId = productionInfo.produceTaskId;
          this.addForm.produceTaskName = productionInfo.produceTaskName;
          this.addForm.productCode = workOrderInfo.productCode;
          this.addForm.productModel = workOrderInfo.model;
          this.addForm.productName = workOrderInfo.productName;
          this.addForm.reportWorkType = productionInfo.reportWorkType;
          this.addForm.specification = workOrderInfo.specification;
          this.addForm.workOrderCode = workOrderInfo.code;
          this.addForm.workOrderId = workOrderInfo.id;
          this.addForm.itemTaskName = productionInfo.itemTaskName;
          this.addForm.ruleId = productionInfo.ruleId;
          this.addForm.brandNo = productionInfo.brandNo;
        }

        console.log('this.productionInfo', this.productionInfo);
        console.log('this.addForm', this.addForm);
      },
      handleBeforeClose() {
        this.type = 'edit';
        this.addForm = JSON.parse(JSON.stringify(this.formDate));
        console.log('this.$refs.ruleFormRef', this.addForm);
        this.$refs.ruleFormRef?.clearValidate();
        this.$nextTick(() => {
          this.visible = false;
        });
      },
      // 提交
      submit(type) {
        console.log('this.addForm', this.addForm);

        // 验证表单
        this.$refs.ruleFormRef.validate(async (valid) => {
          if (!valid) {
            return;
          }

          // 提交
          this.butLoading = true;
          try {
            const body = JSON.parse(JSON.stringify(this.addForm));

            // 工时小时转毫秒
            body.duration = Number(body.duration);
            body.duration = body.duration * 60 * 60 * 1000;

            await saveRuleRecord(body);
            this.$message.success('报工成功！');

            this.butLoading = false;

            // 返回
            this.$emit('reload');

            this.handleBeforeClose();
          } catch (error) {
            this.butLoading = false;
          }
        });
      },
      durationChagne() {
        // 保留小数后一位
        if (
          this.addForm.duration &&
          this.addForm.duration.toString().includes('.')
        ) {
          this.addForm.duration = Number(this.addForm.duration).toFixed(1);
        }
      },
      async getTeamList(id) {
        if (!id) return;
        const ids = id.split(',');
        this.teamList = [];
        this.teamUserList = [];
        const list = ids.map((item) => getTeam(item));

        const dataList = await Promise.all(list);

        dataList.forEach((item) => {
          this.teamList.push({
            name: item.name,
            id: item.id
          });

          this.teamAllList.push(item.userVOList);
        });
      },
      checkTeamList(id) {
        const index = this.teamList.findIndex((item) => item.id == id);
        this.teamUserList = this.teamAllList[index];
        console.log('this.teamUserList', this.teamUserList);
      },
      changeId() {
        if (this.addForm.executeUsersIds.length == this.teamUserList.length) {
          this.checked = true;
        } else {
          this.checked = false;
        }

        const deleteUserIds = this.addForm.executeUsers
          .map((i) => i.userId)
          .filter((id) => !this.addForm.executeUsersIds.includes(id));

        const addUserIds = this.addForm.executeUsersIds.filter(
          (id) => !this.addForm.executeUsers.map((i) => i.userId).includes(id)
        );

        // 删除 用户
        if (deleteUserIds.length > 0) {
          this.addForm.executeUsers = this.addForm.executeUsers.filter(
            (item) => !deleteUserIds.includes(item.userId)
          );
        }

        // 添加 用户
        addUserIds.forEach((id) => {
          const user = this.teamUserList.find((item) => item.id === id);
          if (user) {
            this.addForm.executeUsers.push({
              teamId: this.addForm.teamId,
              teamName: this.teamList.find(
                (team) => team.id == this.addForm.teamId
              )?.name,
              userId: user.id,
              userName: user.name
            });
          }
        });

        console.log('this.addForm.executeUsers', this.addForm.executeUsers);

        this.computedDuration();

        // 同步详情执行人
        this.addForm.details.forEach((detail) => {
          detail.checkUsersIds = this.addForm.executeUsersIds;
          detail.checkUsers = this.addForm.executeUsers;
        });
      },
      // 计算工时
      computedDuration() {
        if (
          this.addForm.checkStartTime &&
          this.addForm.checkFinishTime &&
          this.addForm.executeUsersIds.length > 0
        ) {
          const start = new Date(this.addForm.checkStartTime);
          const finish = new Date(this.addForm.checkFinishTime);
          const diff = finish - start; // 毫秒差值
          const hours = diff / (1000 * 60 * 60); // 转换为小时
          const totalDuration = hours * this.addForm.executeUsersIds.length;
          this.addForm.duration = totalDuration.toFixed(1);
        }
      },
      checkChange() {
        this.addForm.executeUsersIds = [];
        if (this.checked) {
          this.addForm.executeUsersIds = this.teamUserList.map(
            (item) => item.id
          );
        } else {
          this.addForm.executeUsersIds = [];
        }
      },
      // 获取详情
      async getCacheInfo() {
        this.loading = true;
        try {
          const data = await getById(this.productionInfo.recordId);
          console.log('dat 缓存', data);

          this.$util.assignObject(this.addForm, data);

          // 工时毫秒转小时
          this.addForm.duration = (
            this.addForm.duration /
            (1000 * 60 * 60)
          ).toFixed(2);

          this.addForm.recordRulesClassify += '';

          this.addForm.executeUsersIds = this.addForm.executeUsers.map(
            (i) => i.userId
          );

          this.addForm.teamId =
            this.addForm.executeUsers.length > 0
              ? this.addForm.executeUsers[0].teamId
              : '';

          // 加载班组人员列表
          if (this.addForm.teamId) {
            const index = this.teamList.findIndex(
              (item) => item.id == this.addForm.teamId
            );
            this.teamUserList = this.teamAllList[index];
            console.log('this.teamUserList', this.teamUserList);
          }

          console.log('this.addForm', this.addForm);

          this.loading = false;
        } catch (error) {
          this.loading = false;
        }
      }
    }
  };
</script>

<style scoped lang="scss">
  .modal-body {
    padding: 16px;
    min-height: 100px;
  }
  .modal-footer {
    display: flex;
    align-items: center;
    gap: 10px;
    justify-content: flex-end;
  }

  .el-form-item .el-form-item {
    margin-bottom: -5px;
  }

  .checkboxWrapper {
    padding: 8px 20px;
    border-bottom: 1px solid #ccc;
  }

  ::v-deep .el-select__tags {
    flex-wrap: nowrap;
    overflow: auto;
  }

  /* 输入框最大宽度*/
  ::v-deep .el-select__tags-text {
    max-width: 90px;
  }

  /* 底部滚动条的高度*/
  ::v-deep .el-select__tags::-webkit-scrollbar {
    height: 2px !important;
  }
</style>
