<template>
  <div>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="order_form"
    >
      <el-col :span="24">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工号搜索">
              <el-input
                v-model="usercodeSearch"
                placeholder="请输入工号"
                @blur="getUserData"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请科室" prop="ApplicationDept">
              <select-dept-tree
                :deptparam="deptidArr"
                @post-deptid="getDeptid"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室电话" prop="DeptPhone">
              <el-input
                v-model="ruleForm.DeptPhone"
                placeholder="请输入科室电话"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="申请人" prop="Applicant">
              <el-select
                v-model="ruleForm.Applicant"
                filterable
                placeholder="请选择申请人"
                style="width: 100%"
                @change="changeRepairman"
              >
                <el-option
                  v-for="item in repairman"
                  :key="item.usercode"
                  :label="item.username"
                  :value="item.usercode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="ruleForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室位置" prop="position">
              <el-input
                v-model="ruleForm.position"
                type="text"
                placeholder="请输入科室位置"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="typeAlias === 'YQT'">
          <el-col>
            <el-form-item label="设备信息" required>
              <el-button
                :disabled="butIsDisabled"
                icon="el-icon-plus"
                @click="addItem()"
                >添加</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="typeAlias === 'YQT'">
          <el-row v-for="(item, index) in devList" :key="index">
            <el-col :span="7">
              <el-form-item prop="devname">
                <el-select
                  :disabled="butIsDisabled"
                  v-model="item.devname"
                  placeholder="请选择设备"
                  @change="selectChange"
                >
                  <el-option
                    v-for="item in airArr"
                    :key="item.F_DictionaryValueId"
                    :label="item.F_Name"
                    :value="`${item.F_Name},${item.F_DictionaryValueId}`"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item prop="num">
                <el-input-number
                  :disabled="butIsDisabled"
                  v-model="item.num"
                  :min="1"
                  size="mini"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item prop="F_IsBorrow">
                <el-radio-group
                  :disabled="butIsDisabled"
                  v-model="item.F_IsBorrow"
                >
                  <el-radio label="1">借</el-radio>
                  <el-radio label="2">还</el-radio>
                </el-radio-group>
                <el-button
                  type="primary"
                  icon="el-icon-close"
                  circle
                  @click="removeItem(index)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
        <el-row v-if="typeAlias === '2001'">
          <el-col>
            <el-form-item label="设备信息" required>
              <el-button
                :disabled="butIsDisabled"
                icon="el-icon-plus"
                @click="addItem()"
                >添加</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="typeAlias === '2001'">
          <el-row v-for="(item, index) in devList" :key="index">
            <el-col :span="7">
              <el-form-item prop="devname">
                <el-select
                  :disabled="butIsDisabled"
                  v-model="item.devname"
                  placeholder="请选择设备"
                  @change="selectChange"
                >
                  <el-option
                    v-for="item in equipArr"
                    :key="item.F_DictionaryValueId"
                    :label="item.F_Name"
                    :value="`${item.F_Name},${item.F_DictionaryValueId}`"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item prop="num">
                <el-input-number
                  :disabled="butIsDisabled"
                  v-model="item.num"
                  :min="1"
                  size="mini"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item prop="F_IsBorrow">
                <el-radio-group
                  :disabled="butIsDisabled"
                  v-model="item.F_IsBorrow"
                >
                  <el-radio label="1">借</el-radio>
                  <el-radio label="2">还</el-radio>
                </el-radio-group>
                <el-button
                  type="primary"
                  icon="el-icon-close"
                  circle
                  @click="removeItem(index)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>

        <el-row v-if="typeAlias === '2002'">
          <el-col>
            <el-form-item label="物资信息">
              <el-button
                :disabled="butIsDisabled"
                icon="el-icon-plus"
                @click="addItem()"
                >添加</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="typeAlias === '2002'">
          <el-row v-for="(item, index) in devList" :key="index">
            <el-col :span="12">
              <el-form-item prop="devname">
                <el-select
                  :disabled="butIsDisabled"
                  v-model="item.devname"
                  placeholder="请选择物资"
                >
                  <el-option
                    v-for="item in goodsArr"
                    :key="item.F_DictionaryValueId"
                    :label="item.F_Name"
                    :value="`${item.F_Name},${item.F_DictionaryValueId}`"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="num">
                <el-input-number
                  :disabled="butIsDisabled"
                  v-model="item.num"
                  :min="1"
                  size="medium"
                />
                <el-button
                  type="primary"
                  icon="el-icon-close"
                  circle
                  @click="removeItem(index)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>

        <el-row v-if="typeAlias === '2003'">
          <el-col>
            <el-form-item label="病床信息" required>
              <el-button
                :disabled="butIsDisabled"
                icon="el-icon-plus"
                @click="addItem()"
                >添加</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="typeAlias === '2003'">
          <el-row v-for="(item, index) in devList" :key="index">
            <el-col :span="7">
              <el-form-item prop="devname">
                <el-select
                  :disabled="butIsDisabled"
                  v-model="item.devname"
                  placeholder="请选择病床"
                >
                  <el-option
                    v-for="item in bedsArr"
                    :key="item.F_DictionaryValueId"
                    :label="item.F_Name"
                    :value="`${item.F_Name},${item.F_DictionaryValueId}`"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item prop="num">
                <el-input-number
                  :disabled="butIsDisabled"
                  v-model="item.num"
                  :min="1"
                  size="mini"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item prop="F_IsBorrow">
                <el-radio-group
                  :disabled="butIsDisabled"
                  v-model="item.F_IsBorrow"
                >
                  <el-radio label="1">借</el-radio>
                  <el-radio label="2">还</el-radio>
                </el-radio-group>
                <el-button
                  type="primary"
                  icon="el-icon-close"
                  circle
                  @click="removeItem(index)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>

        <el-row v-if="typeAlias === '2006'">
          <el-col>
            <el-form-item label="标本信息" required>
              <el-button
                :disabled="butIsDisabled"
                icon="el-icon-plus"
                @click="addItem()"
                >添加</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="typeAlias === '2006'">
          <el-row v-for="(item, index) in devList" :key="index">
            <el-col :span="12">
              <el-form-item prop="devname">
                <el-cascader
                  ref="cascaderbb"
                  :options="bborderData"
                  :props="TagProps"
                  clearable
                  placeholder="请选择标本"
                  @change="(devname) => handleChange(devname, index)"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="num">
                <el-input-number
                  :disabled="butIsDisabled"
                  v-model="item.num"
                  :min="1"
                  size="medium"
                />
                <el-button
                  type="primary"
                  icon="el-icon-close"
                  circle
                  @click="removeItem(index)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>

        <el-row v-if="typeAlias === '2007'">
          <el-col>
            <el-form-item label="送达科室" required>
              <el-button
                :disabled="butIsDisabled"
                icon="el-icon-plus"
                @click="addItem()"
                >添加</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="typeAlias === '2007'">
          <el-row v-for="(item, index) in devList" :key="index">
            <el-col :span="7">
              <el-form-item prop="F_ToDept">
                <el-cascader
                  ref="cascaderdept"
                  filterable
                  v-model="item.F_ToDept"
                  :options="deptorderData"
                  :props="DeptTagProps"
                  clearable
                  placeholder="请选择科室"
                  @change="(F_ToDept) => handleDeptChange(F_ToDept, index)"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item prop="devname">
                <el-select
                  :disabled="butIsDisabled"
                  v-model="item.devarr"
                  multiple
                  collapse-tags
                  placeholder="请选择血液类型"
                  @change="(devarr) => getBloodsarr(devarr, index)"
                >
                  <el-option
                    v-for="item in bloodArr"
                    :key="item.F_DictionaryValueId"
                    :label="item.F_Name"
                    :value="`${item.F_Name},${item.F_DictionaryValueId}`"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item prop="num">
                <el-input-number
                  :disabled="butIsDisabled"
                  v-model="item.num"
                  :min="1"
                  size="mini"
                />
                <el-button
                  type="primary"
                  icon="el-icon-close"
                  circle
                  @click="removeItem(index)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>

        <el-row v-if="typeAlias === '2005'">
          <el-col>
            <el-form-item label="药品信息">
              <el-button
                :disabled="butIsDisabled"
                icon="el-icon-plus"
                @click="addItem()"
                >添加</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="typeAlias === '2005'">
          <el-row v-for="(item, index) in devList" :key="index">
            <el-col :span="12">
              <el-form-item prop="devname">
                <el-select
                  :disabled="butIsDisabled"
                  filterable
                  allow-create
                  default-first-option
                  v-model="item.devname"
                  placeholder="请选择药品"
                >
                  <el-option
                    v-for="item in drugArr"
                    :key="item.F_DictionaryValueId"
                    :label="item.F_Name"
                    :value="`${item.F_Name},${item.F_DictionaryValueId}`"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="num">
                <el-input-number
                  :disabled="butIsDisabled"
                  v-model="item.num"
                  :min="1"
                  size="medium"
                />
                <el-button
                  type="primary"
                  icon="el-icon-close"
                  circle
                  @click="removeItem(index)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>

        <el-col v-if="typeAlias === '2004'" :span="12">
          <el-form-item label="处方数量">
            <el-input-number
              :disabled="butIsDisabled"
              v-model="ruleForm.cfnum"
              :min="1"
              size="medium"
              class="inputNumber"
            />
          </el-form-item>
        </el-col>

        <!-- <el-row v-if="typeAlias === '2006'">
          <el-col :span="24">
            <el-form-item label="送达地点" prop="toplace">
              <el-select v-model="ruleForm.toplace" filterable placeholder="请选择送达地点" style="width: 100%;">
                <el-option v-for="(item,index) in placeArr" :key="index" :label="item.F_Name" :value="item.F_Name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <!-- <el-row v-if="typeAlias !== '2006'">
          <el-col :span="24">
            <el-form-item label="送达地点" prop="toplace">
              <el-input v-model="ruleForm.toplace" type="text" placeholder="请输入送达地点" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="content">
              <el-input
                v-model="ruleForm.content"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传附件" prop="repairImageid">
              <el-upload
                :headers="headers"
                :file-list="fileList"
                :on-remove="handle_remove"
                :on-success="handle_success"
                :action="imgUrl"
                list-type="picture-card"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="10">
            <el-form-item label="紧急情况">
              <el-radio-group v-model="ruleForm.EmergencyTypes">
                <el-radio label="一般">一般</el-radio>
                <el-radio label="紧急">紧急</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col v-if="iswomanage != 1 && iswomanage != 2" :span="24">
            <el-form-item label="处理方式" prop="opt">
              <el-radio-group v-model="ruleForm.opt">
                <el-radio label="0">立即办理</el-radio>
                <el-radio label="1">暂存</el-radio>
                <el-radio label="2">转派</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          v-if="ruleForm.opt == '2' && iswomanage != 1 && iswomanage != 2"
        >
          <el-col :span="12">
            <el-form-item label="指派科室">
              <select-dept-tree
                :deptparam="deptidArr1"
                @post-deptid="getDeptid1"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="typeAlias !== '2007'" :span="12">
            <el-form-item label="接收人">
              <el-select
                v-model="ruleForm.clid"
                clearable
                filterable
                placeholder="请选择接收人"
                style="width: 100%"
                @change="changeRepairman1"
              >
                <el-option
                  v-for="item in repairman1"
                  :key="item.usercode"
                  :label="item.username + '(' + item.count + ')'"
                  :value="item.usercode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="typeAlias === '2007'">
            <el-table :data="devList">
              <el-table-column prop="F_ToDept" label="送达科室" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.F_ToDept">{{
                    $store.getters.deptmap[parseInt(scope.row.F_ToDept)].text
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="devname" label="血液类型" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.devname.split("?")[0] }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="num" label="数量" align="center" />
              <el-table-column
                prop="F_AssignUser"
                label="指派人"
                align="center"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.F_AssignUser"
                    clearable
                    filterable
                    placeholder="请选择接收人"
                    style="width: 100%"
                    @change="changeRepairman1"
                  >
                    <el-option
                      v-for="item in repairman1"
                      :key="item.usercode"
                      :label="item.username + '(' + item.count + ')'"
                      :value="item.usercode"
                    />
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button type="primary" @click="submitForm">提交工单</el-button>
          </el-form-item>
        </el-row>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import {
  GetDicValueList,
  GetequipList,
  AddSchedulingWorkOrder,
  UpdateSchedulingWorkOrder,
  GetOrderDetail,
} from "@/api/comDispatch/addOrEditDispatch";
import { getUserMsg } from "@/api/orderManagement/orderList";
import { getDeptTree } from "@/api/systemSetup/roleSetting/userManage";
import {
  GetPerson,
  GetDicValue,
  getClassByDeptId,
  GetBBXXList,
} from "@/api/commonAPI";
import { getTypeDetail } from "@/api/systemSetup/roleSetting/department";
import { Send, ws } from "../../../utils/telWebsocket.js";
import { mapGetters } from "vuex";
export default {
  name: "AddOrEditDispatch",
  props: {
    ordreId: {
      type: Number,
      default: 0,
    },
    orderTypeData: {
      type: Object,
      default() {
        return {};
      },
    },
    layerid: {
      type: String,
      default: "",
    },
    callid: {
      type: String,
      default: "",
    },
    wid: {
      type: String,
      default: "",
    },
    fid: {
      type: String,
      default: "",
    },
    iswomanage: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      usercodeSearch: "",
      typeAlias: "",
      cid: "",
      butIsDisabled: false,
      butIsDisabledMyList: false,
      headers: {
        Authorization: "Bearer " + localStorage.getItem("Admin-Token"),
      },
      imgUrl:
        this.$store.getters.serverConfig.BASE_API +
        "FaultRepair/UploadFile?token=" +
        localStorage.getItem("Admin-Token"),
      type2Arr: [],
      firstOrderTypeParam: {
        typeid: 1,
        name: "",
        pid: 0,
      },
      hospitalsParam: {
        id: 0,
        name: "",
      },
      departmentsParam: {
        id: 0,
        name: "",
      },
      repairmanParam: {
        id: 0,
        name: "",
      },
      devList: [
        {
          devname: "",
          num: 1,
          F_IsBorrow: "",
          F_ToDept: "",
          F_AssignUser: "",
        },
      ],
      TagProps: {
        checkStrictly: true,
        value: "id",
        label: "text",
        children: "children",
        emitPath: false,
      },
      DeptTagProps: {
        checkStrictly: true,
        children: "children",
        label: "text",
        value: "id",
        emitPath: false,
      },
      autodeptid: [],
      bborderData: [],
      deptorderData: [],
      placeArr: [],
      detailists: [],
      deptidArr: [],
      deptidArr1: [],
      repairman: [],
      repairman1: [],
      airArr: [],
      equipArr: [],
      goodsArr: [],
      bedsArr: [],
      bloodArr: [],
      // specimenArr: [],
      // fjcspecimenArr: [],
      drugArr: [],
      fileList: [],
      ruleForm: {
        orderType: 2003, // 工单类型
        F_Type2: "",
        ApplicationDept: "",
        DeptPhone: "",
        Applicant: "",
        hospital: 0, // 院区
        department: "", // 科室
        deptid: 0, // 科室id
        username: 0, // 申请人
        usercode: 0, // 申请人id
        phone: "", // 联系电话
        position: "",
        // toplace: "",
        content: "",
        cfnum: "",
        opt: "2",
        clid: "",
        EmergencyTypes: "",
        remark: "", // 备注
        repairImageid: "",
      },
      rules: {
        ApplicationDept: [
          {
            required: true,
            message: "请选择申请科室",
            trigger: "change",
          },
        ],
        Applicant: [
          {
            required: true,
            message: "请选择申请人",
            trigger: "change",
          },
        ],
        position: [
          {
            required: true,
            message: "科室位置不能为空",
            trigger: "blur",
          },
        ],
        // toplace: [{
        //   required: true,
        //   message: '送达地点不能为空',
        //   trigger: 'blur'
        // }],
        // content: [{
        //   required: true,
        //   message: '工单内容不能为空',
        //   trigger: 'blur'
        // }],
        phone: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
          // {
          //   pattern: /^((0\d{2,3}-\d{5,8})|(1[345789]\d{9}))$/,
          //   message: '请输入正确的电话号码或者固话号码',
          //   trigger: 'blur'
          // }
        ],
      },
    };
  },
  watch: {
    "orderTypeData.F_Type2": function () {
      console.log(this.orderTypeData, "7777778888888888");
      this.getTreebiaoben(this.orderTypeData.F_TypeName2);
      this.type2Arr = this.orderTypeData.type2Arr;
      console.log(this.type2Arr[0]);
      this.devList = [
        {
          devname: "",
          num: 1,
          F_IsBorrow: "",
          F_ToDept: "",
        },
      ];
      if (this.type2Arr.length > 0) {
        this.typeAlias =
          this.$store.getters.workTypeMap[parseInt(this.type2Arr[0])].tag || "";
        console.log(this.typeAlias, "标识11");
      }
      this.ruleForm.F_Type2 = this.orderTypeData.F_Type2;

      //默认
      if (this.orderTypeData.F_Type2) {
        this.getAuto();
        // this.deptidArr1 = this.$store.getters.deptmap[parseInt(autodept)].ids
        // this.autodeptid = this.$store.getters.workTypeMap[parseInt(this.orderTypeData.F_Type2)].autoDept
        // if(this.autodeptid){
        //   this.deptidArr1 = this.$store.getters.deptmap[parseInt(this.autodeptid)].ids
        //   this.ruleForm.DealDept = this.$store.getters.workTypeMap[parseInt(this.orderTypeData.F_Type2)].autoDept
        //   this.getClassUser(this.autodeptid)
        // }else{
        //   this.deptidArr1 = []
        //   this.repairman1 = []
        //   this.ruleForm.DealDept = ''
        //   this.ruleForm.clid = ''
        // }
      }
    },
  },
  computed: {
    ...mapGetters([
      "telTopRightState", // 状态信息
    ]),
  },
  created() {
    this.cid = this.callid;
    if (!this.cid) {
      this.cid = window.localStorage.getItem("callidSave");
    }
    this.getairs();
    this.getequis();
    this.getgoods();
    this.getbeds();
    this.getbloods();
    this.getTreeDeptList();
    // this.getbiaoben()
    // this.getTreebiaoben()
    // this.getfjcbiaoben()
    this.getdrugs();
    this.getPlace();
    if (this.wid) {
      this.butIsDisabled = true;
      this.getDetail();
      if (this.iswomanage === "2") {
        this.butIsDisabledMyList = true;
      }
    }
    if (this.iswomanage === "1") {
      this.usercodeSearch = window.localStorage.getItem("storageUsercode");
      const deptid = this.$store.getters.teamId;
      this.deptidArr = this.$store.getters.deptmap[parseInt(deptid)].ids;
      this.ruleForm.ApplicationDept = deptid;
      this.getRepairman(deptid, 0);
      this.getDeptAddress(deptid);
      this.ruleForm.Applicant = this.$store.getters.usercode;
      this.ruleForm.phone = this.$store.getters.mobile;
      this.ruleForm.position = this.$store.getters.location;
      // this.ruleForm.toplace = this.$store.getters.location
    }
    if (this.iswomanage == 1) {
      this.ruleForm.clid = "";
      this.ruleForm.DealDept = "";
    }
    // this.getUserData()
  },
  methods: {
    getAuto() {
      this.deptidArr1 = [];
      this.repairman1 = [];
      this.ruleForm.DealDept = "";
      this.ruleForm.clid = "";
      const autoData = JSON.parse(
        this.$store.getters.workTypeMap[parseInt(this.orderTypeData.F_Type2)]
          .autoDept || "[]"
      );
      const applyHos = this.deptidArr[0];
      console.log(autoData, applyHos);
      if (!autoData) {
        return;
      }
      var hosall = [];
      for (var i = 0; i < autoData.length; i++) {
        hosall.push(autoData[i].autoyq);
      }
      for (var i = 0; i < autoData.length; i++) {
        if (autoData[i].autoyq == applyHos) {
          //有院区
          this.deptidArr1 =
            this.$store.getters.deptmap[parseInt(autoData[i].autodept)].ids;
          this.ruleForm.DealDept = autoData[i].autodept;
          this.getClassUser(autoData[i].autodept);
          this.ruleForm.clid = autoData[i].autousercode;
        } else if (autoData[i].autoyq == "0" && hosall.indexOf(applyHos) < 0) {
          //全部
          this.deptidArr1 =
            this.$store.getters.deptmap[parseInt(autoData[i].autodept)].ids;
          this.ruleForm.DealDept = autoData[i].autodept;
          this.getClassUser(autoData[i].autodept);
          this.ruleForm.clid = autoData[i].autousercode;
        }
      }
    },
    changeMuter(data) {},
    getBloodsarr(val, index) {
      var namestr = "";
      var idstr = "";
      for (var i = 0; i < val.length; i++) {
        namestr += val[i].split(",")[0] + ",";
        idstr += val[i].split(",")[1] + ",";
      }
      this.devList[index].devname =
        namestr.slice(0, namestr.length - 1) +
        "?" +
        idstr.slice(0, idstr.length - 1);
    },
    getTreebiaoben(str) {
      const params = {
        flag: 1,
        typename: str,
      };
      GetBBXXList(params).then((res) => {
        this.bborderData = res.data;
      });
    },
    getTreeDeptList() {
      return new Promise((resolve) => {
        const params = {};
        getDeptTree(params).then((response) => {
          if (response.state.toLowerCase() === "success") {
            this.deptorderData = response.data;
          }
        });
        resolve();
      });
    },
    handleChange(data, index) {
      const obj = this.$refs["cascaderbb"][index].getCheckedNodes();
      this.devList[index].devname = obj[0].data.text + "," + data;
    },
    handleDeptChange(data, index) {
      const obj = this.$refs["cascaderdept"][index].getCheckedNodes();
      if (obj) {
        this.devList[index].F_ToDept = obj[0].data.id;
      }
    },
    getUserData() {
      if (!this.usercodeSearch) {
        return;
      }
      const params = {
        usercode: this.usercodeSearch,
      };
      getUserMsg(params).then((res) => {
        const data = res.data;
        this.ruleForm.ApplicationDept = data.F_DeptId;
        this.deptidArr =
          this.$store.getters.deptmap[parseInt(data.F_DeptId)].ids;
        this.getRepairman(data.F_DeptId, 0);
        this.getDeptAddress(data.F_DeptId);

        this.ruleForm.Applicant = data.F_UserCode;
        this.ruleForm.phone = data.F_Telephone;
        this.ruleForm.position = data.F_Location;
        this.getAuto();
        // this.ruleForm.toplace = data.F_Location
      });
    },
    getPlace() {
      GetDicValue("SDKS").then((res) => {
        this.placeArr = res.rows;
      });
    },
    addItem() {
      const params = {
        devname: "",
        num: 1,
        F_IsBorrow: "",
        F_ToDept: "",
      };
      this.devList.push(params);
    },
    removeItem(index) {
      console.log(index);
      this.devList.splice(index, 1);
    },
    selectChange(val) {
      console.log(val);
    },
    getDeptid(data) {
      this.deptidArr = data;
      this.ruleForm.ApplicationDept = data[data.length - 1];
      this.ruleForm.Applicant = "";
      this.getRepairman(data[data.length - 1], 0);
      this.getDeptAddress(data[data.length - 1]);
      this.getAuto();
    },
    getDeptid1(data) {
      this.ruleForm.DealDept = data[data.length - 1];
      this.getClassUser(data[data.length - 1]);
    },
    getDeptAddress(id) {
      getTypeDetail(id).then((res) => {
        this.ruleForm.position = res.data.F_Location;
        this.ruleForm.DeptPhone = res.data.F_OfficeTelephone;
      });
    },
    getClassUser(id) {
      const params = {
        deptid: id,
      };
      this.repairman1 = [];
      this.ruleForm.clid = "";
      if (id) {
        getClassByDeptId(params).then((res) => {
          this.repairman1 = res.rows;
        });
      }
    },
    getRepairman(id, state) {
      return new Promise((resolve) => {
        const params = {
          deptid: id, // 字典管理的工单标识
        };
        GetPerson(params).then((res) => {
          if (state === 0) {
            this.repairman = res.rows;
          } else if (state === 1) {
            this.assignman = res.rows;
          }
        });
        resolve();
      });
    },
    getRepairman1(id, state) {
      return new Promise((resolve) => {
        const params = {
          deptid: id, // 字典管理的工单标识
        };
        GetPerson(params).then((res) => {
          if (state === 0) {
            this.repairman1 = res.rows;
          } else if (state === 1) {
            this.assignman1 = res.rows;
          }
        });
        resolve();
      });
    },
    changeRepairman(data) {
      const user = this.repairman.find((o) => {
        return o.usercode === data.toString();
      });
      if (user) {
        this.ruleForm.phone = user.usertelphone;
      }
    },
    changeRepairman1(data) {},
    handle_success(res) {
      this.ruleForm.repairImageid += res.data[0].F_FileId + ",";
    },
    handle_remove(res) {
      if (res.F_FileId) {
        var oldstr = res.F_FileId + ",";
      }
      if (res.response) {
        var str = res.response.data[0].F_FileId + ",";
      }
      if (oldstr) {
        this.ruleForm.repairImageid = this.ruleForm.repairImageid.replace(
          oldstr,
          ""
        );
      }
      if (str) {
        this.ruleForm.repairImageid = this.ruleForm.repairImageid.replace(
          str,
          ""
        );
      }
    },
    getairs() {
      const params = {
        Flag: "YQT",
        Name: "",
      };
      return new Promise((resolve) => {
        GetDicValueList(params).then((response) => {
          this.airArr = response.rows;
        });
        resolve();
      });
    },
    getequis() {
      const params = {
        Flag: "SBXX",
        Name: "",
      };
      return new Promise((resolve) => {
        GetDicValueList(params).then((response) => {
          this.equipArr = response.rows;
        });
        resolve();
      });
    },
    getgoods() {
      const params = {
        Flag: "WZXX",
        Name: "",
      };
      GetDicValueList(params).then((res) => {
        this.goodsArr = res.rows;
      });
    },
    getbeds() {
      const params = {
        Flag: "BCXX",
        Name: "",
      };
      GetDicValueList(params).then((res) => {
        this.bedsArr = res.rows;
      });
    },
    getbloods() {
      const params = {
        Flag: "XYLX",
        Name: "",
      };
      GetDicValueList(params).then((res) => {
        this.bloodArr = res.rows;
      });
    },
    // getbiaoben() {
    //   const params = {
    //     Flag: 'BBXX',
    //     Name: ''
    //   }
    //   GetDicValueList(params).then((res) => {
    //     this.specimenArr = res.rows
    //   })
    // },
    // getfjcbiaoben() {
    //   const params = {
    //     Flag: 'abc',
    //     Name: ''
    //   }
    //   GetDicValueList(params).then((res) => {
    //     this.fjcspecimenArr = res.rows
    //   })
    // },
    getdrugs() {
      const params = {
        Flag: "YPXX",
        Name: "",
      };
      GetDicValueList(params).then((res) => {
        this.drugArr = res.rows;
      });
    },
    getDetail() {
      const datas = {
        WorkOrderCode: this.wid,
      };
      // 详情
      GetOrderDetail(datas)
        .then((response) => {
          if (response.state.toLowerCase() === "success") {
            const res = response.data[0];
            this.firstOrderTypeParam.name = res.TypeName;
            this.$emit("r2type", res.F_WorkOrderCategory);
            this.ruleForm.F_Type2 = res.F_WorkOrderCategory;
            if (res.F_WorkOrderCategory) {
              this.type2Arr =
                this.$store.getters.workTypeMap[
                  parseInt(res.F_WorkOrderCategory)
                ].ids.slice(1);
              this.typeAlias =
                this.$store.getters.workTypeMap[parseInt(this.type2Arr[0])].tag;
            }
            if (res.F_ApplicationDept) {
              this.deptidArr =
                this.$store.getters.deptmap[
                  parseInt(res.F_ApplicationDept)
                ].ids;
              this.getRepairman(res.F_ApplicationDept, 0);
              this.getDeptAddress(res.F_ApplicationDept);
              this.ruleForm.ApplicationDept = res.F_ApplicationDept;
              this.ruleForm.Applicant = res.F_Applicant;
            }
            if (res.F_DealDept) {
              this.ruleForm.opt = "2";
              this.deptidArr1 =
                this.$store.getters.deptmap[parseInt(res.F_DealDept)].ids;
              this.getRepairman1(res.F_DealDept, 0);
              this.ruleForm.DealDept = res.F_DealDept;
              this.ruleForm.clid = res.F_DealMan;
            } else {
              this.ruleForm.opt = "2";
            }
            if (res.FileUrl) {
              for (var i = 0; i < res.FileUrl.length; i++) {
                this.ruleForm.repairImageid += res.FileUrl[i].F_FileId + ",";
                this.fileList.push({
                  F_FileId: res.FileUrl[i].F_FileId,
                  name: res.FileUrl[i].F_FileName,
                  url: res.FileUrl[i].F_FileUrl,
                });
              }
            }
            this.ruleForm.cfnum = res.F_RemindCount;
            this.ruleForm.phone = res.F_Phone;
            this.ruleForm.position = res.F_Location;
            this.ruleForm.content = res.F_Content;
            this.usercodeSearch = res.F_Applicant;
            // this.ruleForm.toplace = res.F_ToPlace
            // this.ruleForm.EmergencyTypes = res.F_EmergencyTypes
            // const jcarr = []
            // const fjcarr = []
            // this.specimenArr.forEach(function(v, n) {
            //   jcarr.push(v.F_DictionaryValueId)
            // })
            // this.fjcspecimenArr.forEach(function(v, n) {
            //   fjcarr.push(v.F_DictionaryValueId)
            // })
            const arr = [];
            res.PSInfo.forEach(function (v, n) {
              arr.push({
                devname: v.F_DicName + "," + v.F_DicId,
                num: v.F_Number,
              });
              // if(jcarr.indexOf(v.F_DicId)>=0){
              //   arr.push({
              //     devname: v.F_DicName + ',' + v.F_DicId,
              //     num: v.F_Number,
              //     muterType:'0'
              //   })
              // }
              // if(fjcarr.indexOf(v.F_DicId)>=0){
              //   arr.push({
              //     devname: v.F_DicName + ',' + v.F_DicId,
              //     num: v.F_Number,
              //     muterType:'1'
              //   })
              // }
            });
            this.devList = arr;
          }
        })
        .catch(() => {});
    },
    getUrl() {
      if (window.location.href.indexOf("callScreen") >= 0) {
        this.$store.dispatch("delView", this.$route);
        const scoketDatas = {
          Type: "SayFree",
          AgentID: window.localStorage.getItem("storageUsercode"),
          AgentExten: window.localStorage.getItem("ext"),
        };
        if (this.telTopRightState == "话后处理中") {
          Send(scoketDatas);
        }
        window.sessionStorage.setItem("isBusyOrFree", 1); // 0是置忙1是置闲
        this.$router.push({
          path: "/Dashboard",
        });
      }
      // else {
      //   window.location.reload()
      // }
    },
    submitForm() {
      // console.log(this.devList)
      // return;
      if (this.orderTypeData.type2Arr.length == 0 && !this.wid) {
        this.$message.error("请选择工单类别");
        return;
      }
      if (
        this.typeAlias === "2001" ||
        this.typeAlias === "2003" ||
        this.typeAlias === "YQT" ||
        this.typeAlias === "2006" ||
        this.typeAlias === "2007"
      ) {
        if (this.devList.length == 0) {
          this.$message.error("请选择对应物资信息");
          return;
        }
      }
      if (
        this.typeAlias === "2001" ||
        this.typeAlias === "2003" ||
        this.typeAlias === "YQT"
      ) {
        if (this.devList.length > 0 && !this.devList[0].F_IsBorrow) {
          this.$message.error("请选择对应物资信息");
          return;
        }
      }
      if (this.typeAlias === "2007") {
        this.ruleForm.clid = "";
        if (this.devList.length > 0 && !this.devList[0].F_ToDept) {
          this.$message.error("请选择对应物资信息");
          return;
        }
      }
      if (this.telTopRightState == "通话中") {
        if (window.location.href.indexOf("callScreen") >= 0) {
          this.$message("请挂断后再提交工单");
          return;
        }
      }
      var details = [];
      let isNull = false;
      if (this.typeAlias !== "2004") {
        var this_ = this;
        this.devList.forEach(function (v, n) {
          if (!isNull && !v.devname) {
            isNull = true;
          }
          if (
            this_.typeAlias === "2001" ||
            this_.typeAlias === "2003" ||
            this_.typeAlias === "YQT"
          ) {
            details.push({
              F_DicId: v.devname.split(",")[1],
              F_DicName: v.devname.split(",")[0],
              F_Number: v.num,
              F_IsBorrow: v.F_IsBorrow,
            });
          } else if (this_.typeAlias === "2007") {
            details.push({
              F_DicId: v.devname.split("?")[1],
              F_DicName: v.devname.split("?")[0],
              F_Number: v.num,
              F_ToDept: v.F_ToDept,
              F_AssignUser: v.F_AssignUser,
            });
          } else {
            details.push({
              F_DicId: v.devname.split(",")[1],
              F_DicName: v.devname.split(",")[0],
              F_Number: v.num,
            });
          }
        });
      }
      // console.log(details)
      // return;
      if (isNull) {
        if (
          this.typeAlias === "2001" ||
          this.typeAlias === "2003" ||
          this.typeAlias === "2006" ||
          this.typeAlias === "2007" ||
          this.typeAlias === "YQT"
        ) {
          this.$message.error("请选择对应物资信息");
          return;
        } else {
          details = [];
        }
      }
      if (this.iswomanage == 1 || this.iswomanage == 2) {
        this.ruleForm.DealDept = "";
        this.ruleForm.clid = "";
        this.ruleForm.opt = "1";
      }
      if (this.ruleForm.opt == "0") {
        details = [];
      }
      if (this.ruleForm.opt == "0" || this.ruleForm.opt == "1") {
        this.ruleForm.DealDept = "";
        this.ruleForm.clid = "";
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.ruleForm.repairImageid === "") {
            this.ruleForm.repairImageid = "";
          } else {
            this.ruleForm.repairImageid = this.ruleForm.repairImageid.slice(
              0,
              this.ruleForm.repairImageid.length - 1
            );
          }
          var datas = {
            CallId: this.cid,
            CallRecordsId: "",
            LeaveRecordId: this.fid,
            ApplicationDept: this.ruleForm.ApplicationDept,
            Applicant: this.ruleForm.Applicant,
            phone: this.ruleForm.phone,
            DeptPhone: this.ruleForm.DeptPhone,
            Location: this.ruleForm.position,
            WorkOrderCategory: this.ruleForm.F_Type2,
            // ToPlace: this.ruleForm.toplace,
            Content: this.ruleForm.content,
            opt: this.ruleForm.opt,
            DealDept: this.ruleForm.DealDept,
            DealMan: this.ruleForm.clid,
            // EmergencyTypes: this.ruleForm.EmergencyTypes,
            File: this.ruleForm.repairImageid,
            detailists: details,
          };
          var editdatas = {
            usertype: "1",
            WorkOrderCode: this.wid,
            ApplicationDept: this.ruleForm.ApplicationDept,
            Applicant: this.ruleForm.Applicant,
            phone: this.ruleForm.phone,
            DeptPhone: this.ruleForm.DeptPhone,
            Location: this.ruleForm.position,
            WorkOrderCategory: this.ruleForm.F_Type2,
            // ToPlace: this.ruleForm.toplace,
            Content: this.ruleForm.content,
            opt: this.ruleForm.opt,
            DealDept: this.ruleForm.DealDept,
            DealMan: this.ruleForm.clid,
            // EmergencyTypes: this.ruleForm.EmergencyTypes,
            File: this.ruleForm.repairImageid,
            detailists: details,
          };
          // 添加
          if (this.wid) {
            if (this.iswomanage === "1") {
              editdatas.usertype = 1;
            } else {
              editdatas.usertype = 1;
            }
            UpdateSchedulingWorkOrder(editdatas)
              .then((response) => {
                if (response.state.toLowerCase() === "success") {
                  // this.$parent.$layer.closeAll()
                  // this.$parent.$layer.close(this.layerid)
                  // this.$parent.getList() // 重新加载父级数据
                  this.$emit("closeLayer");
                  this.$message.success("恭喜你，修改成功!");
                  this.usercodeSearch = "";
                }
              })
              .catch(() => {});
          } else {
            AddSchedulingWorkOrder(datas)
              .then((response) => {
                if (response.state.toLowerCase() === "success") {
                  this.getUrl();
                  this.$parent.$layer.closeAll();
                  // this.$parent.$layer.close(this.layerid)
                  // this.$parent.getList() // 重新加载父级数据
                  // this.$refs.ruleForm.resetFields()
                  // this.$message.success('恭喜你，添加成功!')
                  // this.fileList = []
                  // this.ruleForm.repairImageid = ''
                  if (window.location.href.indexOf("addWorkOrder") >= 0) {
                    this.$message({
                      message: "工单已提交成功！",
                      type: "success",
                      duration: 500,
                    });
                    this.$router.push({
                      path: "/orderManage/mySubmit",
                    });
                  } else {
                    this.$message({
                      message: "恭喜你，添加工单成功！",
                      type: "success",
                      duration: 500,
                    });
                  }
                }
              })
              .catch(() => {});
          }
        }
      });
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss">
.addOp span {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  background-color: #409eff;
  color: #fff;
  vertical-align: middle;
  margin-right: 5px;
  cursor: pointer;
}
</style>
