<template>
  <!-- 添加或修改项目信息对话框 -->
  <el-dialog
    title="部门信息"
    v-model="visible"
    width="500px"
    append-to-body
    draggable
  >
    <div class="form-container">
      <el-form
        ref="deptRef"
        class="master-container"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item v-if="adminPower" label="当前厂别" prop="tenantId">
          <el-select-v2
            v-model="form.tenantId"
            :options="tenantList"
            placeholder="请选择厂别"
            style="width: 500px"
          />
        </el-form-item>
        <el-form-item label="上级部门" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="deptOptions"
            :props="{
              value: 'deptId',
              label: 'deptName',
              children: 'children',
            }"
            value-key="deptId"
            placeholder="请选择上级部门"
            check-strictly
            :render-after-expand="false"
          >
          </el-tree-select>
        </el-form-item>

        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model.trim="form.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="deptCode">
          <el-input v-model.trim="form.deptCode" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item
          v-if="form.type === '0'"
          label="是否为工段"
          prop="isWorkSection"
        >
          <el-select
            v-model="form.isWorkSection"
            placeholder="请选择是否为工段"
          >
            <el-option
              v-for="item in work_section_status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="自动分配任务" prop="autoAllocation">
         <el-select
             v-model="form.autoAllocation"
         >
           <el-option
               v-for="item in yes_no"
               :key="item.value"
               :label="item.label"
               :value="item.value"
           ></el-option>
         </el-select>
       </el-form-item> -->
        <!--        <el-form-item label="自动解绑载具" prop="autoUnbind">-->
        <!--          <el-select-->
        <!--              v-model="form.autoUnbind"-->
        <!--          >-->
        <!--            <el-option-->
        <!--                v-for="item in yes_no"-->
        <!--                :key="item.value"-->
        <!--                :label="item.label"-->
        <!--                :value="item.value"-->
        <!--            ></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item label="是否一机多批" prop="equimentFlag">
          <el-select v-model="form.equimentFlag">
            <el-option
              v-for="item in yes_no"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否分选" prop="isSortPackaging">
          <el-select v-model="form.isSortPackaging">
            <el-option
              v-for="item in yes_no"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否外协" prop="isOutsourcing">
          <el-select
            v-model="form.isOutsourcing"
            @change="handleChanceOutsourcing"
          >
            <el-option
              v-for="item in yes_no"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.isOutsourcing == 1"
          label="外协商"
          prop="supplierName"
        >
          <el-input
            v-model.trim="form.supplierName"
            :disabled="true"
            placeholder="请选择外协商"
          >
            <template #append>
              <el-button icon="Search" @click="handleSelectSupplierSingle" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number
            v-model="form.orderNum"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="submitForm"
        >确 定</el-button
      >
      <el-button icon="Close" @click="cancel">取 消</el-button>
    </template>
    <select-supplier-dialog
      ref="selectSupplierRef"
      :single-selected="handleSingleSelectedSupplier"
    />
  </el-dialog>
</template>
<script setup>
import { listDept, getDept, saveDept } from "@/api/system/dept";
import { listTenant } from "@/api/business/tenant";
import { checkReturnReceiptDetail } from "@/api/business/returnReceiptDetail";
import useUserStore from "@/store/modules/user";
import selectSupplierDialog from "./DialogSupplierSelect";
const { proxy } = getCurrentInstance();
/** 字典数组区 */
const { work_section_status } = proxy.useDict("work_section_status");
const { yes_no } = proxy.useDict("yes_no");

/** 表单抽屉 页变量 */
const visible = ref(false);
const adminPower = ref(false);
const deptOptions = ref([]);
const disabled = ref(false);
const tenantList = ref([]);
const data = reactive({
  form: {},
  rules: {
    parentId: [{ required: true, message: "请选择上级部门", trigger: "blur" }],
    tenantId: [{ required: true, message: "请选择厂别", trigger: "blur" }],
    deptName: [
      { required: true, message: "部门名称不能为空", trigger: "blur" },
    ],
    deptCode: [
      { required: true, message: "部门编码不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "显示排序不能为空", trigger: "blur" },
    ],
  },
});
const { form, rules } = toRefs(data);
const emit = defineEmits(["handleSaveSuccess"]);
/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(row) {
  reset();

  //判断当前厂别是否为0
  adminPower.value = useUserStore().user.tenantId == 0 ? true : false;
  if (adminPower.value) {
    //获得厂别信息
    getTenantList();
  }
  visible.value = true;
  listDept().then((response) => {
    response.rows = response.rows.filter((item) => {
      return item.type == "0";
    });
    deptOptions.value = deptOptions.value.concat(
      proxy.handleTree(response.rows, "deptId")
    );
    deptOptions.value.unshift({ deptId: "0", deptName: "无", children: [] });
  });
  if (row) {
    getDept(row.id).then((response) => {
      response.data.isSortPackaging = response.data.isSortPackaging + "";
      response.data.isOutsourcing = response.data.isOutsourcing + "";
      console.log(response.data);
      form.value = response.data;
    });
  }
  disabled.value = true;
}
function getTenantList() {
  listTenant().then((res) => {
    tenantList.value = res.rows.map((v) => ({ value: v.id, label: v.orgName }));
  });
}
/** 取消按钮 */
function cancel() {
  visible.value = false;
  reset();
}
function handleChanceOutsourcing(val) {
  if (val == 0) {
    form.value.supplierName = "";
    form.value.supplierId = 0;
  }
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    deptId: "",
    type: "0",
    companyId: "0",
    parentId: "",
    code: "",
    name: "",
    remark: "",
    isWorkSection: "0",
    sort: 0,
    equimentFlag: "0",
    autoAllocation: "0",
    isSortPackaging: "0",
    isOutsourcing: "0",
    supplierId: 0
  };
  disabled.value = false;
  deptOptions.value = [];
  proxy.resetForm("deptRef");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate((valid) => {
    if (valid) {
      console.log(form.value);
      if (form.value.isOutsourcing == 1 && form.value.supplierId == 0) {
          proxy.$modal.msgError("外协商不能为空");
        }else{
          if(form.value.deptId == ""){
            saveDept(form.value).then((res) => {
            if (res.code === 200) {
              proxy.$modal.msgSuccess("操作成功");
              emit("handleSaveSuccess");
            }
            visible.value = false;
          });
          }else{
            console.log("999")
            //编辑
            if (form.value.isOutsourcing == 1 ) {
            //外协商判断
            checkReturnReceiptDetail(form.value).then((res) => {
              if (res.data) {
                saveDept(form.value).then((res) => {
                  if (res.code === 200) {
                    proxy.$modal.msgSuccess("操作成功");
                    emit("handleSaveSuccess");
                  }
                  visible.value = false;
                });
              }else{
                proxy.$modal.msgError("之前外协商存在外协明细未收回");
              }
            });
          }else{
            saveDept(form.value).then((res) => {
            if (res.code === 200) {
              proxy.$modal.msgSuccess("操作成功");
              emit("handleSaveSuccess");
            }
            visible.value = false;
          });
          }
          }
        }
    }
  });
}
//打开选择外协商弹窗
function handleSelectSupplierSingle() {
  proxy.$refs.selectSupplierRef.open(
    form.value.deptId == "" ? 0 : form.value.deptId
  );
}
//外协商带回
function handleSingleSelectedSupplier(row) {
  form.value.supplierId = row.id;
  form.value.supplierName = row.name;
}

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
